如何在后台Python中运行子流程命令以启动Node.js服务器

问题描述

我已经通过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')

它将按照以下顺序进行:

  1. “子流程命令的输出
  2. 仅在服务器停止运行后:“继续”
  3. “正在运行其他代码...”
  4. “一旦停止设置,此方法将运行”

解决方法

您可以使用python的线程模块来创建和运行线程。我创建了一个测试JS脚本文件后,该代码应该可以正常工作了,实际上,这一次它是在其他代码运行时打开的:

from threading import Thread
import subprocess
import time

def runServer():
  print('Starting server...\n')
  output = subprocess.run(["node",'script.js'])
  print('Done running server...')

server = Thread(target=runServer) #you can create as many threads as you need
server.start()

#other code goes here
for x in range(0,15):
    print(x)
    time.sleep(1)

script.js:

console.log('Starting script...')
setTimeout(function(){ console.log("Script finished"); },10000);

输出:

Starting server...
0

1
2
3
4
5
6
7
8
9
10
Done running server...
11
12
13
14

如您所见,服务器在其他代码运行时完成运行。希望您在运行此程序时不会有任何问题,但是请告诉我您是否这样做。