gpt4 book ai didi

python - 子进程中的 sys.stdin.read() 永远不会返回

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:23 24 4
gpt4 key购买 nike

我正在尝试理解 subprocess.Popen 和 subprocess.PIPE。在这样做的同时,我创建了三个小脚本。

本练习的目标是,使用一个脚本打印数据,从另一个脚本读取数据并将其回显给第一个脚本。

问题是,最后一个 sys.stdin.read() 会阻止整个代码正常工作。

测试.py

#!/usr/bin/python3

from subprocess import Popen, PIPE

proc1 = Popen(["python3","script1.py"], stdin=PIPE, stdout=PIPE)
proc2 = Popen(["python3","script2.py"], stdin=PIPE, stdout=PIPE)

first_output = proc1.stdout.read()

print("[test.py:] " + str(first_output))

proc2.stdin.write(first_output)
proc2.stdin.flush()
proc2.stdin.close()

answer = proc2.stdout.read()

print("[test.py:] " + str(answer))

proc1.stdin.write(answer)

script1.py

import sys

sys.stdout.write("Hello world")
sys.stdout.flush()

answer = str(sys.stdin.read())

script1.py 中的最后一行 answer = str(sys.stdin.read()) 导致整个程序卡住。如果我将其注释掉,一切正常。

为什么会这样,为什么我无法进一步沟通?我还没有找到答案。

script2.py

import sys

input_read = str(sys.stdin.read())

sys.stdout.write("[script2.py:] " + input_read + " input read")
sys.stdout.flush()

最佳答案

当你这样做时:

first_output = proc1.stdout.read()

这会尝试读取 proc1 必须说的所有内容;也就是说,它一直读取直到文件句柄关闭。这不会发生,因为 proc1 本身正在等待读取:

answer = str(sys.stdin.read())

使用管道在进程之间进行通信可能有点棘手。我建议通读 the documentation for the subprocess module .

为了解决您眼前的问题,我知道两个简单的解决方案。一种是改用线路通信。在script1.py中,写一个换行符:

sys.stdout.write("Hello world\n")
sys.stdouf.flush()

answer = str(sys.stdin.readline())

然后在 script2.py 中添加一个换行符并切换到 readline:

input_read = str(sys.stdin.readline())

sys.stdout.write("[script2.py:] " + input_read + " input read\n")
sys.stdout.flush()

另一种方法是切换到使用 read1而不是阅读。它需要一个参数来表示要读取的字节数,但不会等到接收那么多数据后再返回。

关于python - 子进程中的 sys.stdin.read() 永远不会返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524758/

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