繁体   English   中英

python子进程挂起读取管道

[英]python subprocess hang on reading a pipe

我有这个,但最后管道的子进程读取挂起:

$cat waitforinput.sh
#!/bin/sh


while read line
do
echo $line
done                    


>>> p1 = subprocess.Popen(["/home/abc/waitforinput.sh", "-v"], shell=True, executable=None,stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> 
>>> 
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> 
>>> 
>>> p1.stdin.flush()
>>> 
>>> for i in p1.stdout:
...     print i 
... 

我应该怎么做才能不挂?

而不是flush(),调用p1.stdin.close()

...
p1.stdin.write('This is good idea\n')
p1.stdin.write('This is good idea\n')

p1.stdin.close()

for i in p1.stdout:
    print i

UPDATE

用stdout.readline()替换带有while循环的 stdout-iteration

参考python manpage -u part:

强制stdin,stdout和stderr完全无缓冲。 在重要的系统上,还将stdin,stdout和stderr置于二进制模式。 请注意,xread- lines(),readlines()和file-object迭代器(“for sys.stdin中的行”)中存在内部缓冲,不受此选项的影响。 要解决此问题,您需要在“while 1:”循环中使用“sys.stdin.readline()”。

p1.stdin.flush()

while True:
    line = p1.stdout.readline()
    if not line:
        break
    print line

您将获得输出,但没有close() ,脚本将不会结束。 无论如何你应该使用close()

问题是waitforinput.sh正在缓冲其输出。 falsetru的解决方案有效,因为close会导致脚本退出并刷新其输出缓冲区。 这是处理流水线命令的常用方法。

如果您想以交互方式输出输出,可以使用pty模块或pexpect来欺骗脚本,使其认为它正在写入终端。 然后,它的输出将只是行缓冲。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM