最近我试图编写一个简单的python代码,它应该使用stdin
与另一个进程进行通信。这是我到目前为止尝试的:
文件start.py
:
import sys
from subprocess import PIPE, Popen
proc = subprocess.Popen(["python3", "receive.py"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
proc.stdin.write(b"foon")
proc.stdin.flush()
print(proc.stdout.readline())
文件receive.py
:
import sys
while True:
receive = sys.stdin.readline().decode("utf-8")
if receive == "END":
break
else:
if receive != "":
sys.stdout.write(receive + "-" + receive)
sys.stdout.flush()
不幸的是,当我python3 start.py
结果时,我得到了b''
.我应该如何回答另一个进程的提示?
子流程提前结束。您可以通过打印子流程的stderr
来检查它。
# after proc.stdin.flush()
print(proc.stderr.read())
错误信息:
Traceback (most recent call last):
File "receive.py", line 4, in <module>
receive = sys.stdin.readline().decode()
AttributeError: 'str' object has no attribute 'decode'
子流程提前结束的原因
sys.stdin.readline()
返回一个字符串(不是字节字符串(;尝试针对字符串调用decode
会导致 Python 3.x 中的 AttributeError。
要解决此问题,请删除decode(..)
呼叫receive.py
:
receive = sys.stdin.readline() # without decode.
并且,要使start.py
完整,请发送END
,并关闭子流程的stdin
;让子流程优雅地完成。
proc.stdin.write(b"foon")
proc.stdin.flush()
print(proc.stdout.readline())
proc.stdin.write(b'END') # <---
proc.stdin.close() # <---
# proc.wait()