簡體   English   中英

如何運行子進程命令在后台啟動 nodejs 服務器 Python

[英]How to run a subprocess command to start a nodejs server in the background Python

我已經通過subprocess進程調用成功啟動了節點服務器腳本,並在 python 中捕獲了 output:

subprocess.check_output(["node", "path/to/script"])

現在,因為 python 是同步的,所以它不會在上面那行之后運行任何代碼,因為它正在等待服務器“完成”。 我需要使用該命令運行節點腳本,然后立即允許該行之后的所有代碼,但能夠從服務器捕獲每個 output。

這可能嗎?

編輯:

在 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);

Output:

Starting server...
0

1
2
3
4
5
6
7
8
9
10
Done running server...
11
12
13
14

如您所見,服務器在其他代碼運行時完成運行。 希望您在運行時不會遇到任何問題,但如果遇到問題請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM