【问题标题】:sys.stdin.read() in subprocess never returning子进程中的 sys.stdin.read() 永远不会返回
【发布时间】: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


【解决方案1】:

当你这样做时:

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 而不是读取。它需要一个参数来表示要读取的字节数,但在返回之前不会等待接收那么多数据。

【讨论】:

  • 感谢您指出我的错。我发现启用两个进程之间的通信有点困难。我将尝试使用 readline()。我已经阅读了有关子流程的文档。我将仔细研究阅读的文档。
  • 它按我的预期工作。 readline() 是要走的路。谢谢!
  • 乐于助人!
猜你喜欢
  • 2020-11-05
  • 2019-11-15
  • 2011-07-25
  • 1970-01-01
  • 2012-10-02
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多