【问题标题】:How to run a subprocess command to start a nodejs server in the background Python如何运行子进程命令以在后台 Python 中启动 nodejs 服务器
【发布时间】:2020-08-19 14:05:55
【问题描述】:

我已经通过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 node.js python-3.x subprocess


【解决方案1】:

您可以使用 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

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

【讨论】:

  • 正是我需要的,谢谢!我假设asyncio.run(main()) 之后的任何内容都会在两者都完成后运行?
  • 干杯,很好的答案!
  • 经过一些测试,node.js 服务器运行时没有运行任何代码,甚至其他异步函数中的代码也没有运行。我需要在服务器运行时运行代码,然后在代码完成后停止服务器...?
  • 好的。我正在研究它
  • 没问题,可能只有我一个人,但我认为您的解决方案会奏效,我不明白为什么没有?谢谢
猜你喜欢
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 2017-11-02
  • 2019-03-06
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
相关资源
最近更新 更多