python子进程模块:循环子进程的stdout


问题内容

我有一些正在使用子流程模块运行的命令。然后,我想循环输出的行。文档说不执行data_stream.stdout.read,我不是,但是我可能正在做一些调用该操作的事情。我正在这样循环输出:

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

这会导致死锁,例如从data_stream.stdout中读取数据吗?还是将Popen模块设置为此类循环,以便它使用通信代码但为您处理所有调用?


问题答案:

如果要与子进程进行 通信
,则必须担心死锁,即,如果要写入stdin以及从stdout读取数据。因为这些管道可能会被缓存,所以进行这种双向通信非常不行:

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),则应该没问题。

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

如果需要双向通信,请使用communication