我已经通过 subprocess
调用成功启动了一个 Node 服务器脚本,并在 python 中捕获了输出:
subprocess.check_output(["node", "path/to/script"])
现在,因为 python 是同步的,所以它不会在上面那行之后运行任何代码,因为它正在等待服务器“完成”。我需要使用该命令运行 Node 脚本,然后立即允许该行之后的所有代码,但能够捕获服务器的每个输出。
这可能吗?
编辑:
在 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 的线程模块来创建和运行线程。这次代码应该可以工作,因为我创建了一个测试 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)
脚本.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
如您所见,服务器在其他代码运行时完成运行。希望您在运行时不会遇到任何问题,但如果遇到问题请告诉我。
关于python - 如何运行子进程命令以在后台 Python 中启动 nodejs 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63488797/