如何 运行 子进程命令在后台启动 nodejs 服务器 Python
How to run a subprocess command to start a nodejs server in the background Python
我已经通过 subprocess
调用成功启动了节点服务器脚本,并在 python 中捕获了输出:
subprocess.check_output(["node", "path/to/script"])
现在,因为 python 是同步的,所以它不会 运行 上面那行之后的任何代码,因为它正在等待服务器 'finish'。我需要使用该命令 运行 节点脚本,然后立即允许该行之后的所有代码,但能够捕获服务器的每个输出。
这可能吗?
编辑:
在 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')
它将按以下顺序送达:
- 'Output of the subprocess command'
- 仅在服务器停止后:'continuing'
- 'Running other code...'
- 'THIS WILL RUN ONCE THE SEVER HAS SETUP HAS STOPPED'
您可以使用 python 的线程模块来创建和 运行 线程。这次代码应该可以工作,因为我创建了一个测试 JS 脚本文件,这次它确实打开了,而另一个代码是 运行ning:
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
如您所见,服务器完成 运行ning 而另一个代码是 运行ning。希望您在 运行 执行此操作时不会遇到任何问题,但如果遇到问题请告诉我。
我已经通过 subprocess
调用成功启动了节点服务器脚本,并在 python 中捕获了输出:
subprocess.check_output(["node", "path/to/script"])
现在,因为 python 是同步的,所以它不会 运行 上面那行之后的任何代码,因为它正在等待服务器 'finish'。我需要使用该命令 运行 节点脚本,然后立即允许该行之后的所有代码,但能够捕获服务器的每个输出。
这可能吗?
编辑:
在 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')
它将按以下顺序送达:
- 'Output of the subprocess command'
- 仅在服务器停止后:'continuing'
- 'Running other code...'
- 'THIS WILL RUN ONCE THE SEVER HAS SETUP HAS STOPPED'
您可以使用 python 的线程模块来创建和 运行 线程。这次代码应该可以工作,因为我创建了一个测试 JS 脚本文件,这次它确实打开了,而另一个代码是 运行ning:
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
如您所见,服务器完成 运行ning 而另一个代码是 运行ning。希望您在 运行 执行此操作时不会遇到任何问题,但如果遇到问题请告诉我。