提问者:小点点

如何在后台Python中运行子进程命令来启动nodejs服务器


我已经通过一个子进程调用成功地启动了一个节点服务器脚本,并在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')

它的顺序是:

  1. '子进程命令的输出'
  2. 仅在服务器停止后:“继续”
  3. “正在运行其他代码。。。”
  4. '这将在服务器安装程序停止后运行'

共1个答案

匿名用户

使用内置的asyncio库和asyncio.Gather,可以并发运行函数。下面是一个概念验证/演示,您可以将代码填入其中:

import asyncio
#import subprocess

async def runNodeScript():
    print('Running script...')
    await asyncio.sleep(1) #simulate lengthy tasks
    print('Done with script')
    #You'd place the subprocess call here (though obviously first removing the demo code above):
    #subprocess.check_output(["node", "path/to/script"])

async def runOtherCode():
    print('Running other code...') #place the code below the subprocess call here
    
async def main():
    await asyncio.gather( #run functions concurrently
        runNodeScript(),
        runOtherCode()
        )

asyncio.run(main())
print('Done with everything')

输出:

Running script...
Running other code...
Done with script
Done with everything

[Program finished]

这是我做的一个repl,这样你就可以在线测试和编辑代码了。