子进程输出到 PIPE 并直接输出到 stdout
Output of subprocess both to PIPE and directly to stdout
我发现了一些看起来像我的问题,但没有产生我可以使用的解决方案(最接近的是:subprocess output to stdout and to PIPE)
问题:我想使用需要很长时间的子进程启动一个进程。在 运行 命令之后,我需要解析标准输出和标准错误输出。
目前我是这样操作的:
p = subprocess.Popen( command_list, stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
out, error_msg = p.communicate()
print out + "\n\n" + error_msg
#next comes code in which I check out and error_msg
但这种方法的缺点是用户在 运行 时看不到过程的输出。仅在最后打印输出。
有没有一种方法可以在命令为 运行 时打印输出(就像我在没有 stdout/stderr=subprocess.PIPE 的情况下发出命令一样)并且仍然通过 p.communicate到底是?
注意:我目前正在开发 python 2.5(使用此 python 版本的旧软件版本)。
这段代码曾在类似情况下帮助过我:
process = subprocess.Popen(cmd, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
print line,
sys.stdout.flush() # please see comments regarding the necessity of this line
process.wait()
errcode = process.returncode
我发现了一些看起来像我的问题,但没有产生我可以使用的解决方案(最接近的是:subprocess output to stdout and to PIPE)
问题:我想使用需要很长时间的子进程启动一个进程。在 运行 命令之后,我需要解析标准输出和标准错误输出。
目前我是这样操作的:
p = subprocess.Popen( command_list, stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
out, error_msg = p.communicate()
print out + "\n\n" + error_msg
#next comes code in which I check out and error_msg
但这种方法的缺点是用户在 运行 时看不到过程的输出。仅在最后打印输出。
有没有一种方法可以在命令为 运行 时打印输出(就像我在没有 stdout/stderr=subprocess.PIPE 的情况下发出命令一样)并且仍然通过 p.communicate到底是?
注意:我目前正在开发 python 2.5(使用此 python 版本的旧软件版本)。
这段代码曾在类似情况下帮助过我:
process = subprocess.Popen(cmd, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
print line,
sys.stdout.flush() # please see comments regarding the necessity of this line
process.wait()
errcode = process.returncode