简体   繁体   English

如何在python中用子进程监视stdout?

[英]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.stdoutp.stdoutp依次在其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.

相关问题 我如何在Windows上的python中测试子进程的stdout,stderr - how do i test subprocess's stdout, stderr in python on windows 在python中使用subprocess.call时如何将stdout重定向到文件? - How do I redirect stdout to a file when using subprocess.call in python? 在杀死用python子进程Popen启动的进程时,如何关闭stdout-pipe? - How do I close the stdout-pipe when killing a process started with python subprocess Popen? 在 python 中,如何检查 subprocess.Popen 对象的标准输出是否有任何要读取的内容? - In python, How do I check the stdout from a subprocess.Popen object for anything to read? 如何清除Python子进程中的stdout? - How to clear stdout in Python subprocess? 我正在寻找一个有关如何将select.select()与子进程一起使用以监视stdout的示例 - I'm looking for an example on how to use select.select() with subprocess to monitor stdout 如何正确循环 subprocess.stdout - How do I properly loop through subprocess.stdout 如何在unittest中捕获python子进程stdout - How to capture python subprocess stdout in unittest 如何在不通信的情况下读取python子进程标准输出 - How to read python subprocess stdout without communicate Python:如何以非阻塞方式读取子进程的标准输出 - Python: How to read stdout of subprocess in a nonblocking way
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM