如何使用python中的子进程监视stdout? [英] how do I monitor stdout with subprocess in python?
问题描述
我有一个 linux 应用程序,它使用 stdin 从命令行交互运行以接受命令.我已经编写了一个包装器,使用子进程在应用程序处于后台时访问 stdin.我现在可以使用 p.stdin.write(command) 向它发送命令,但是我该如何监控它的响应呢?
I have a linux application that runs interactively from commandline using stdin to accept commands. I've written a wrapper using subprocess to access stdin while the application is backgrounded. I can now send commands to it using p.stdin.write(command) but how do I go about monitoring its responses?
推荐答案
从 p.stdout
读取以访问进程的输出.
Read from p.stdout
to access the output of the process.
根据进程的作用,您可能必须小心确保不会阻塞 p.stdout
而 p
反过来阻塞其 p.stdout
代码>标准输入.如果您确定每次写入时它都会输出一行,您可以简单地像这样循环交替:
Depending on what the process does, you may have to be careful to ensure that you do not block on p.stdout
while p
is in turn blocking on its stdin
. If you know for certain that it will output a line every time you write to it, you can simply alternate in a loop like this:
while still_going:
p.stdin.write('blah\n')
print p.stdout.readline()
但是,如果输出更加零星,您可能需要查看 select
模块以更灵活的方式在读取和写入之间交替.
However, if the output is more sporadic, you might want to look into the select
module to alternate between reading and writing in a more flexible fashion.
这篇关于如何使用python中的子进程监视stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!