【发布时间】:2018-06-19 15:28:22
【问题描述】:
python 新手,目前使用的是 Python 3.5.2。我有一个子进程,我需要在其中监视输出,对其进行处理并通过 kivy 显示它。这工作正常。
但是有一点,子进程需要回复才能继续或退出。这就是我完全陷入困境的地方。
chimp_cmd = 'sudo /usr/bin/mono ' + os.getcwd() + '/aDotNet.exe ' + aVeryLongListofParam # aVeryLongListofParam is read from a file
child = subprocess.Popen([chimp_cmd],
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
bufsize=0) # no difference with bufsize set to 1
# while loop that reads in the data
# do funky stuff with the output data, (this works and relies on a lot of starts with comparisons)
if ( (b''.join(MyOutputLineList).decode("utf-8) ).startswith("Would you like"):
# wait for the thread that gets the response - this works
if usrReply = UsrKeyReply.no:
print("received user no") # we get to here
# attempts at sending a reply:
ret_value = child.stdin.write(b'n\n') # this doesn't work for me
print(ret_value)
print("test1")
os.system('pidof mono') # for debug
elif usrReply = UsrKeyReply.yes:
print("received user yes") # also get to this point
stdout, stderr = child.communicate(input=b'n\n')[0]
# child.stdin.flush() <-- this hangs the code
print("test2") # doesn't work for me either
其他细节。 在 Ubuntu 上。 使用以下命令调用 python 脚本:
sudo python3 myscript.py
是的,它必须是 sudo,因为单声道需要访问 USB 端口。
DotNet.exe 是第三方
如果直接从命令行调用,DotNet.exe 可以正常工作。
我知道消息不会返回到子进程,因为除了没有任何反应之外,我可以打开另一个终端并通过以下方式监视子进程:
sudo strace -p <mono's PID>
在这里,我可以看到 exe 正在运行并与 python 脚本很好地配合,我看到提示“你愿意...”
当 python 脚本到达发送回复的点时,孩子不会终止(当 'n' 时)或继续(当 'y' 时)
救命!
按照@Hermann 的建议,我尝试更改为:
bufsize=1,
universal_newlines=True)
还修改了对
的回复stdout, stderr = child.communicate(input='n\n')[0]
child.stdin.flush()
脚本在此之后挂起。
还有什么想法吗?
【问题讨论】:
标签: c# python subprocess