我有一种情况,当我必须在 asyncio 事件循环中运行子进程时,子进程通信挂起,并且整个过程都在一个单独的线程中。
我了解到为了在单独的线程中运行子进程,我需要有
1. an event loop running in main thread, and
2. a child watcher must be initiated in main thread.
Run Code Online (Sandbox Code Playgroud)
具备上述条件后,我得到了我的子流程工作。但是 subprocess.communicate 现在挂了。如果从主线程调用它,则相同的代码正在工作。
进一步挖掘后,我观察到通信挂起,因为该过程没有自行完成。ie await process.wait()实际上是挂。
当我试图在子进程中发出的命令挂起时,我已经看到通信挂起,但这里的情况并非如此。
import asyncio
import shlex
import threading
import subprocess
async def sendcmd(cmd):
cmdseq = tuple(shlex.split(cmd))
print(cmd)
p = await asyncio.create_subprocess_exec(*cmdseq, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(p.pid)
output = (await asyncio.wait_for(p.communicate(), 5))[0]
output = output.decode('utf8')
print(output)
return output
async def myfunc(cmd):
o = await sendcmd(cmd)
return o
def myfunc2():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) …Run Code Online (Sandbox Code Playgroud)