[英]how do I monitor stdout with subprocess in python?
I have a linux application that runs interactively from commandline using stdin to accept commands. 我有一个Linux应用程序,可以使用stdin从命令行以交互方式运行以接受命令。 I've written a wrapper using subprocess to access stdin while the application is backgrounded. 在应用程序后台运行时,我使用子进程编写了一个包装程序来访问stdin。 I can now send commands to it using p.stdin.write(command) but how do I go about monitoring its responses? 我现在可以使用p.stdin.write(command)向其发送命令,但是如何监视其响应?
Read from p.stdout
to access the output of the process. 从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
. 根据过程的不同,您可能必须小心确保不要在p.stdout
上p.stdout
而p
依次在其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()
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. 但是,如果输出是零星的,则可能需要查看select
模块,以更灵活的方式在读取和写入之间进行切换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.