python子进程模块:循环子进程的标准输出 [英] python subprocess module: looping over stdout of child process

查看:55
本文介绍了python子进程模块:循环子进程的标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些正在使用 subprocess 模块运行的命令.然后我想遍历输出的行.文档说不要做 data_stream.stdout.read 我不是,但我可能正在做一些调用它的事情.我像这样循环输出:

I have some commands which I am running using the subprocess module. I then want to loop over the lines of the output. The documentation says do not do data_stream.stdout.read which I am not but I may be doing something which calls that. I am looping over the output like this:

for line in data_stream.stdout:
   #do stuff here
   .
   .
   .

这会导致死锁,比如从 data_stream.stdout 读取,还是 Popen 模块为这种循环设置,以便它使用通信代码但为您处理它的所有调用?

Can this cause deadlocks like reading from data_stream.stdout or are the Popen modules set up for this kind of looping such that it uses the communicate code but handles all the callings of it for you?

推荐答案

如果您正在与子进程通信,则必须担心死锁,即,如果您正在写入 stdin 以及从标准输出读取.因为这些管道可能会被缓存,所以进行这种双向通信是非常禁忌的:

You have to worry about deadlocks if you're communicating with your subprocess, i.e. if you're writing to stdin as well as reading from stdout. Because these pipes may be cached, doing this kind of two-way communication is very much a no-no:

data_stream = Popen(mycmd, stdin=PIPE, stdout=PIPE)
data_stream.stdin.write("do something\n")
for line in data_stream:
  ...  # BAD!

但是,如果您在构造 data_stream 时没有设置 stdin(或 stderr),应该没问题.

However, if you've not set up stdin (or stderr) when constructing data_stream, you should be fine.

data_stream = Popen(mycmd, stdout=PIPE)
for line in data_stream.stdout:
   ...  # Fine

如果您需要双向通信,请使用 communicate.

If you need two-way communication, use communicate.

这篇关于python子进程模块:循环子进程的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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