我有一些使用子进程模块运行的命令.然后我想循环输出的行.文档说不要做data_stream.stdout.read我不是,但我可能正在做一些调用它的东西.我像这样循环输出:
for line in data_stream.stdout:
#do stuff here
.
.
.
Run Code Online (Sandbox Code Playgroud)
这会导致死锁,例如从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!
Run Code Online (Sandbox Code Playgroud)
但是,如果在构造data_stream时没有设置stdin(或stderr),那么你应该没问题.
data_stream = Popen(mycmd, stdout=PIPE)
for line in data_stream.stdout:
... # Fine
Run Code Online (Sandbox Code Playgroud)
如果您需要双向通信,请使用通信.