【发布时间】:2019-09-23 12:51:20
【问题描述】:
我是 python 新手,我尝试从其他 python 脚本向一个子进程发送信息,但子进程在主进程停止发送之前不会读取任何内容。
我尝试发送以“\n”结尾的新行和行。 我知道我的子进程在流完成之前被阻塞,但是如果我发送 \n 或直接发送 stdin.write('\n'),它应该可以正确读取,但它没有
主要流程:
import subprocess
import time
child = subprocess.Popen("python3 example.py", shell=True, stdin=subprocess.PIPE, universal_newlines=True)
s = "this is the message"
print("MAIN:The child pid is: " + str(child.pid))
for i in range(0, 5):
print("MAIN:iteration send:" + str(i))
msg = s + "-" + str(i) + "\n"
child.stdin.writelines(msg)
time.sleep(1)
child.kill()
子流程:
import time
from sys import stdin
while True:
try:
print("CHILD:before read")
s = stdin.readline()
print("CHILD:after read")
print("CHILD:message received is:" + s)
except EOFError as err:
print("M_READ_ERROR")
time.sleep(1)
我的输出是这样的
MAIN:The child pid is: 18041
MAIN:iteration send:0
CHILD:before read
MAIN:iteration send:1
MAIN:iteration send:2
MAIN:iteration send:3
MAIN:iteration send:4
CHILD:after read
CHILD:message received id:this is the message-0
但我期待的是这样的:
MAIN:The child pid is: 18041
MAIN:iteration send:0
CHILD:before read
CHILD:after read
CHILD:message received id:this is the message-0
MAIN:iteration send:1
CHILD:before read
CHILD:after read
CHILD:message received id:this is the message-1
MAIN:iteration send:2
CHILD:before read
CHILD:after read
CHILD:message received id:this is the message-2
MAIN:iteration send:3
CHILD:before read
CHILD:after read
CHILD:message received id:this is the message-3
MAIN:iteration send:4
CHILD:before read
CHILD:after read
CHILD:message received id:this is the message-4
【问题讨论】:
-
我在您的代码中没有看到
stdin.readline()。您只有stdin.read()与readline()的工作方式不同 -
@furas 我都尝试了,但我上传的版本是我最后一次尝试。已编辑
-
使用
child.stdin.flush()
标签: python python-3.x subprocess stdin