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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With