python - 如何运行子进程命令以在后台 Python 中启动 nodejs 服务器

标签 python node.js python-3.x subprocess

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

它将按照以下顺序出现:

  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)

脚本.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/

相关文章:

python - 具有有限替换的无序组合

node.js - Faker.js v7 清除商店

python - 将列表转换为字典列表

python - PyQt 从用户获取日期

python - Mechanize 中的 HTTP 登录

python - 是否可以在 folium python 中为矩形着色

node.js - out 参数结果由 Node pg 模块返回 - postgresql

Node.js - Sequelize.js 嵌套关联检查外部 where 条件 - 未定义

python-3.x - 使用 Scikit-Learn 在 Python 中绘制多项式回归

python - 检索数据时显示 "Unable to get repr for <class ' django.db.models.query.QuerySet'>"