【发布时间】:2014-02-02 00:11:48
【问题描述】:
我正在使用 python 的subprocess 模块来启动一个新进程。我想实时捕获新进程的输出,以便我可以用它做一些事情(显示它、解析它等)。我已经看到了很多如何做到这一点的例子,一些使用自定义的类似文件的对象,一些使用threading,还有一些尝试读取输出直到进程完成。
File Like Objects Example (click me)
- 我不希望使用自定义的类文件对象,因为我希望允许用户为
stdin、stdout和stderr提供他们自己的值。
- 我真的不明白为什么需要线程,所以我不愿意遵循这个例子。如果有人可以解释为什么线程示例有意义,我会很乐意听。但是,此示例还限制用户提供自己的
stdout和stderr值。
读取输出示例(见下文)
对我来说最有意义的例子是阅读stdout、stderr,直到该过程完成。下面是一些示例代码:
import subprocess
# Start a process which prints the options to the python program.
process = subprocess.Popen(
["python", "-h"],
bufsize=1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# While the process is running, display the output to the user.
while True:
# Read standard output data.
for stdout_line in iter(process.stdout.readline, ""):
# Display standard output data.
sys.stdout.write(stdout_line)
# Read standard error data.
for stderr_line in iter(process.stderr.readline, ""):
# Display standard error data.
sys.stderr.write(stderr_line)
# If the process is complete - exit loop.
if process.poll() != None:
break
我的问题是,
问。是否有推荐的方法来使用 python 捕获进程的输出?
【问题讨论】:
-
可以给个输入输出的例子吗?
-
哈,就是这样!我正在比较不同版本的 python 的输出。菜鸟失误!!我从原始问题中删除了截断问题。谢谢你让我看起来更努力一点。
标签: python subprocess stdout