gpt4 book ai didi

python子进程卡在读取管道上

转载 作者:太空宇宙 更新时间:2023-11-04 10:44:49 25 4
gpt4 key购买 nike

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

$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
...

我应该怎么做才不会挂起?

最佳答案

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

...
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

更新

stdout-iteration 替换为 while-loop with stdout.readline()

引用python manpage -u部分:

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xread‐ lines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.

p1.stdin.flush()

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

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

关于python子进程卡在读取管道上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com