Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have successfully started a node server script through a subprocess call and capture the output in python:

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

Now, because python is synchronous it doesn't run any code after that line above as it's waiting for the server to 'finish'. I need to run the node script by using that command and then immediately allow all code after that line but have the ability to capture every output from the server.

Is this possible?

EDIT:

After MarsNebulaSoup's answer with using asyncio, no code is ran until the nodejs server is stopped:

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')

It will come as this order:

  1. 'Output of the subprocess command'
  2. ONLY AFTER THE SERVER HAS STOPPED: 'continuing'
  3. 'Running other code...'
  4. 'THIS WILL RUN ONCE THE SEVER HAS SETUP HAS STOPPED'
like image 357
Nathan Avatar asked Sep 19 '25 22:09

Nathan


1 Answers

You can use python's threading module to create and run threads. The code should work this time, as I created a test JS script file and, indeed it opens this time, while the other code is running:

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

Output:

Starting server...
0

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

As you can see, the server finishes running while the other code is running. Hopefully you won't have any problems when running this, but let me know if you do.

like image 92
marsnebulasoup Avatar answered Sep 21 '25 11:09

marsnebulasoup