问题是pipe
已满。子进程停止,等待管道清空,但随后进程(Python 解释器)退出,破坏了管道的末尾(因此出现错误消息)。
p.wait()
不会帮助你:
Warning如果子进程生成足够的输出到 stdout 或 stderr 管道,从而阻塞等待操作系统管道缓冲区接受更多数据,这将导致死锁。使用communicate()
以避免这种情况。
http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
p.communicate()
不会帮助你:
Note读取的数据缓冲在内存中,因此如果数据量很大或无限制,请勿使用此方法。
http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate
p.stdout.read(num_bytes)
不会帮助你:
Warning Use communicate()
而不是.stdin.write
, .stdout.read
or .stderr.read
避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致死锁。
http://docs.python.org/library/subprocess.html#subprocess.Popen.stdout
这个故事的寓意是,对于大产量,subprocess.PIPE
如果您的程序试图读取数据,将会注定您会失败(在我看来,您应该能够将p.stdout.read(bytes)
into a while p.returncode is None:
循环,但上面的警告表明这可能会死锁)。
文档建议用以下内容替换 shell 管道:
p1 = Popen(["zgrep", "thingiwant", "largefile"], stdout=PIPE)
p2 = Popen(["processreceivingdata"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
请注意p2
直接从其标准输入p1
. This should避免僵局,但考虑到上述相互矛盾的警告,谁知道.
无论如何,如果最后一部分不适合你(它should,但是),您可以尝试创建一个临时文件,写入第一次调用的所有数据,然后使用临时文件作为下一个进程的输入。