簡體   English   中英

從Python運行shell命令並實時打印輸出

[英]Running shell commands from Python and printing the output in real time

我想編寫一個函數,一次執行多個shell命令,並實時打印shell返回的內容。

我目前有以下不打印外殼的代碼(我正在使用Windows 10和python 3.6.2):

commands = ["foo", "foofoo"]
p = subprocess.Popen("cmd.exe", shell=True, stdin=subprocess.PIPE, \
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for command in commands:
    p.stdin.write((command + "\n").encode("utf-8"))
p.stdin.close()
p.stdout.read()

我如何實時查看外殼返回的內容?

編輯:此問題不是注釋中第一個兩個鏈接的重復,它們無助於實時打印。

我相信你需要這樣的東西

commands = ["foo", "foofoo"]
p = subprocess.Popen("cmd.exe", shell=True, stdin=subprocess.PIPE, \
                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for command in commands:
    p.stdin.write((command + "\n").encode("utf-8"))
out, err = p.communicate()
print("{}".format(out))
print("{}".format(err))

假設您想控制python代碼中的輸出,則可能需要執行以下操作

import subprocess

def run_process(exe):
    'Define a function for running commands and capturing stdout line by line'
    p = subprocess.Popen(exe.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')


if __name__ == '__main__':
    commands = ["foo", "foofoo"]
    for command in commands:
        for line in run_process(command):
            print(line)

可以在不同的線程中處理stdinstdout 這樣,一個線程可以處理打印來自stdout的輸出,而另一個線程可以在stdin上編寫新命令。 但是,由於stdinstdout是獨立的流,因此我認為這不能保證流之間的順序。 對於當前示例,它似乎按預期工作。

import subprocess
import threading

def stdout_printer(p):
    for line in p.stdout:
        print(line.rstrip())

commands = ["foo", "foofoo"]
p = subprocess.Popen("cmd.exe", stdin=subprocess.PIPE, 
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                     universal_newlines=True)

t = threading.Thread(target=stdout_printer, args=(p,))
t.start()

for command in commands:
    p.stdin.write((command + "\n"))
    p.stdin.flush()

p.stdin.close()
t.join()

另外,請注意,我正在逐行編寫stdout ,這通常是可以的,因為它傾向於被緩沖並一次生成一行(或更多)。 我猜有可能代替逐個字符處理無緩沖的stdout流(或stderr ),如果那是更好的話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM