最近我试图编写一个简单的python代码,该代码应该使用backButton.setSelected(false)
与另一个进程通信。这是我到目前为止所尝试的:
档案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"foo\n")
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
。我该如何回答另一个流程的提示?
答案 0 :(得分:1)
子流程提前结束。您可以通过打印子流程的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"foo\n")
proc.stdin.flush()
print(proc.stdout.readline())
proc.stdin.write(b'END') # <---
proc.stdin.close() # <---
# proc.wait()