【发布时间】:2013-06-15 22:15:35
【问题描述】:
是否可以修改下面的代码以从 'stdout' 和 'stderr' 打印输出:
- 在终端上打印(实时),
- 最后存储在 outs 和 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,特别感谢@j-f-sebastian,最终功能:
#!/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和errs并返回它们...要打印到终端,只需if outs: print outsif errs: print errs -
@bnlucas 谢谢,但正如我在第一点所说:输出应该实时打印到终端,就像没有管道一样。
-
如果你需要 Python 3 代码;添加python-3.x 标签(我在shebang中看到python3)。您编写的代码将使阅读线程挂起。在 Python 3 中,
''是一个 Unicode 文字,但pipe.readline()默认返回字节('' != b""在 Python 3 上)。如果你修复它,那么编写器线程将不会结束,因为没有任何东西将""放入队列中。
标签: python python-3.x subprocess popen