如何读取subprocess.stdout管道中当前的所有内容,然后返回? [英] how do I read everything currently in a subprocess.stdout pipe and then return?

查看:42
本文介绍了如何读取subprocess.stdout管道中当前的所有内容,然后返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 的 subprocess 模块通过 stdin 和 stdout 管道与程序交互.如果我在stdout上调用子进程readline(),它将挂起,因为它正在等待换行符.

I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline.

如何读取子流程实例的stdout管道中的所有字符?如果有关系的话,我正在Linux上运行.

How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.

推荐答案

其他人似乎也有同样的问题,您可以查看相关的讨论

Someone else appears to have had the same problem, you can see the related discussion here.

如果您正在Linux上运行,则可以使用select等待该进程的stdout上的输入.或者,您可以使用

If you are running on Linux you can use select to wait for input on the process' stdout. Alternatively you change the mode of the process' stdout to non-blocking using

import fcntl, os 
fcntl.fcntl(your_process.stdout, fcntl.F_SETFL, os.O_NONBLOCK)

之后,您可以使用read()循环直到遇到换行符(如果您想一次处理输出一行).

after which you can loop using read() until you encounter a newline character (if you want to process the output one line at a time).

这篇关于如何读取subprocess.stdout管道中当前的所有内容,然后返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆