如何在后台Python中运行subprocess命令来启动nodejs服务器
我已经通过如何在后台Python中运行subprocess命令来启动nodejs服务器,python,node.js,python-3.x,subprocess,Python,Node.js,Python 3.x,Subprocess,我已经通过子流程调用成功启动了节点服务器脚本,并用python捕获了输出: subprocess.check_output(["node", "path/to/script"]) 现在,因为python是同步的,所以它不会在上面这一行之后运行任何代码,因为它正在等待服务器“完成”。我需要使用该命令运行节点脚本,然后立即允许该行之后的所有代码,但能够捕获服务器的每个输出 这可能吗 编辑: MarsNebulaSoup使用asyncio回答问题后,在停止no
子流程
调用成功启动了节点服务器脚本,并用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的线程模块来创建和运行线程。这段代码这次应该可以运行,因为我创建了一个测试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
如您所见,服务器在其他代码运行时完成运行。希望您在运行此程序时不会遇到任何问题,但如果有问题,请告诉我。您不是说“python是同步的”吗?听起来您需要异步函数:@MarsNebulaSoup ahahahah,是的,很抱歉拼写错误……正是我需要的,谢谢!我假设
asyncio.run(main())
之后的任何东西都将在两者都完成后运行?干杯,回答得好!经过一些测试后,node.js服务器运行时没有运行任何代码,甚至没有其他异步函数中的代码。我需要在服务器运行时运行代码,然后在代码完成后停止服务器…?好的。我正在调查没问题,可能只有我一个人,但我认为你的解决方案会奏效,我不明白为什么不行??谢谢