是否有可能低於修改代碼從「標準輸出」和‘標準錯誤’具有打印輸出:Subprocess.Popen:克隆輸出和錯誤既終端和變量
- 打印終端上(在實時間),
- 最後存儲在出和errs變量?
代碼:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import subprocess
def run_cmd(command, cwd=None):
p = subprocess.Popen(command, cwd=cwd, shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
outs, errs = p.communicate()
rc = p.returncode
outs = outs.decode('utf-8')
errs = errs.decode('utf-8')
return (rc, (outs, errs))
感謝@unutbu,對於@ JF-塞巴斯蒂安特別感謝,最終的功能:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from queue import Queue
from subprocess import PIPE, Popen
from threading import Thread
def read_output(pipe, funcs):
for line in iter(pipe.readline, b''):
for func in funcs:
func(line.decode('utf-8'))
pipe.close()
def write_output(get):
for line in iter(get, None):
sys.stdout.write(line)
def run_cmd(command, cwd=None, passthrough=True):
outs, errs = None, None
proc = Popen(
command,
cwd=cwd,
shell=False,
close_fds=True,
stdout=PIPE,
stderr=PIPE,
bufsize=1
)
if passthrough:
outs, errs = [], []
q = Queue()
stdout_thread = Thread(
target=read_output, args=(proc.stdout, [q.put, outs.append])
)
stderr_thread = Thread(
target=read_output, args=(proc.stderr, [q.put, errs.append])
)
writer_thread = Thread(
target=write_output, args=(q.get,)
)
for t in (stdout_thread, stderr_thread, writer_thread):
t.daemon = True
t.start()
proc.wait()
for t in (stdout_thread, stderr_thread):
t.join()
q.put(None)
outs = ' '.join(outs)
errs = ' '.join(errs)
else:
outs, errs = proc.communicate()
outs = '' if outs == None else outs.decode('utf-8')
errs = '' if errs == None else errs.decode('utf-8')
rc = proc.returncode
return (rc, (outs, errs))
的代碼示例確實店'outs'和'錯誤'並返回它們......要打印到終端,只需簡單地「如果超出:打印輸出''如果錯誤:打印錯誤' – bnlucas
@blulucas謝謝,但正如我在第一點所述:輸出應打印在實時到達終端,就像沒有PIPEing一樣。 –
如果您需要Python 3代碼;添加[tag:python-3.x]標籤(我在shebang中看到python3)。你寫的代碼會讓閱讀線程掛起。在Python 3中''''是一個Unicode文字,但'pipe.readline()'默認返回字節(在Python 3上是'''!= b「」')。如果你修復它,那麼編寫器線程不會結束,因爲沒有把''「'放入隊列中。 – jfs