最近,我一直在试验使用异步的不和谐机器人。我一直在制作一个控制许多其他机器人的程序,在运行中打开和关闭它们,但我有一个问题;我尝试过subprocess.Popen、rpyc和多进程,但我很难想出如何在程序之间进行通信。我尝试使用以下代码来启动子进程:
Popen('python smallprogram.py', stdout=PIPE, stdin=PIPE)但是我仍然无法从主程序到较小的程序进行通信,因为较小的程序需要运行异步。这使我无法在Popen.communicate()中使用input()。理想情况下,我希望有一种方法在需要时调用较小程序上的函数,而小型程序仍在运行异步。我不介意将相同的代码块粘贴到每个较小的程序中,但我认为这也可以通过一些重要的步骤来解决?
这能办到吗?我以前从未做过API,但我似乎需要使用API作为模板。谢谢您:)
注:我只需要做大->小的交流,但做相反的方式也会很好。
发布于 2017-08-21 11:20:52
有多方面来处理进程间的通信,我认为您使用stdin/stdout是一种有效的方法。
事实证明,异步从stdin异步读取是可能的,尽管它是很难做,只使用标准库。
或者,您可以使用观音台助手ainput。
import aioconsole
async def echo_child():
data = await aioconsole.ainput()
print(data, end='')或get_standard_streams用于类似于流API的接口。
import aioconsole
async def echo_child():
stdin, stdout = await aioconsole.get_standard_streams()
data = await stdin.readline()
stdout.write(data)在母公司方面:
import asyncio
async def parent():
proc = await asyncio.create_subprocess_exec(
sys.executable, 'child.py',
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE)
proc.stdin.write(b'Hello\n')
data = await proc.stdout.readline()
print(data.decode().strip())
proc.terminate()https://stackoverflow.com/questions/45785066
复制相似问题