【发布时间】:2020-08-19 14:05:55
【问题描述】:
我已经通过subprocess 调用成功启动了一个节点服务器脚本,并在python 中捕获了输出:
subprocess.check_output(["node", "path/to/script"])
现在,因为 python 是同步的,它不会在上面的那一行之后运行任何代码,因为它正在等待服务器“完成”。我需要使用该命令运行节点脚本,然后立即允许该行之后的所有代码,但能够捕获服务器的每个输出。
这可能吗?
编辑:
在 MarsNebulaSoup 使用 asyncio 回答之后,在 nodejs 服务器停止之前不会运行任何代码:
async def setupServer():
output = subprocess.run(["node", '/path/to/app.js'])
print('continuing')
async def setupController():
print('Running other code...')
async def mainAsync():
await asyncio.gather(setupServer(), setupController())
asyncio.run(mainAsync())
print('THIS WILL RUN ONCE THE SEVER HAS SETUP HAS STOPPED')
它会按照这个顺序来:
- '子进程命令的输出'
- 仅在服务器停止后:“继续”
- '正在运行其他代码...'
- '这将在服务器设置停止后运行'
【问题讨论】:
-
你不是说“python是同步的”吗?
-
听起来你需要异步函数:docs.python.org/3/library/asyncio.html
-
@MarsNebulaSoup 啊哈哈,是的,抱歉拼写错误......
标签: python node.js python-3.x subprocess