【发布时间】:2018-01-30 15:16:56
【问题描述】:
我正在尝试理解 subprocess.Popen 和 subprocess.PIPE。在此过程中,我创建了三个小脚本。
本练习的目标是,使用一个脚本打印数据,从另一个脚本读取数据并将其回显到第一个脚本。
问题是,最后一个 sys.stdin.read() 会阻止整个代码正常工作。
test.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()
【问题讨论】:
-
感谢您指出这一点。围绕“按预期”写一些东西会更好吗?或者你会建议我把标题改成什么?
-
嗯。 sys.stdin.read() in subprocess never returned 将描述该行为,但并不暗示这是因为系统设施未按规范运行。
标签: python python-3.x io