每当客户端(即消费者)连接到我的Django服务器时,我都想在命令行中执行命令,然后打印该命令的返回代码:
from channels.generic.websocket import AsyncWebsocketConsumer
import asyncio
class Consumer(AsyncWebsocketConsumer):
async def do_command(self):
process = await asyncio.create_subprocess_shell('pwd', stdout=asyncio.subprocess.PIPE)
try:
line = await asyncio.wait_for(process.stdout.readline(), 5)
print("line is" + line.decode())
print(process.returncode)
# wait for process to finish so we can check the return code
await asyncio.wait_for(process.wait(), 5)
except asyncio.TimeoutError:
print("process timed out!")
else:
print("process finished successfully!")
finally:
print(process.returncode)
async def connect(self):
asyncio.get_event_loop().create_task(self.do_command())
print("Finished scheduling do_command task")
运行上面的代码,我得到
Finished scheduling do_command task
line is /opt/working_dir/django
None
process timed out!
None
每当客户端连接到我的服务器时。
但是,process.returncode
始终是None
那是为什么?我需要知道命令是否成功。
问题似乎专门与await process.wait
有关。
由于某些原因,该命令永远不会完成执行(即process.returncode
始终为None
)。
但是,以下代码可以正常工作:
import asyncio
async def do_command():
process = await asyncio.create_subprocess_shell(cmd='pwd')
await process.wait()
print("Finished process.wait")
print(process.returncode)
loop = asyncio.get_event_loop()
task = loop.create_task(do_command())
asyncio.get_event_loop().run_until_complete(task)
loop.close()
print("Finished Go Task")
返回:
/opt/working_dir/django
Finished process.wait
0
Finished Go Task