Reputation: 43
Currently I have a Node.JS server that needs to run a python script. Part of this script imports some data from a server that takes time which is detrimental to the experience as this Python script needs to be ran frequently.
What I want is for the Node.JS server to run this Python script when the server is ran, then in the background constantly have it keep running, with the ability to (from the Node.JS server) call a python function that returns data.
So far I have this on the Node.JS server that runs a python script and outputs the response. This is repeated every time data is needed to be retrieved:
const util = require('util'); var options = { mode: 'text', args: [sentenceToUse] };
const readPy = util.promisify(PythonShell.run);
const test = await readPy("spacyTest.py", options);
var response = test.toString();
response = response.toString();
response = response.replace(/'/g, '"');
response = JSON.parse(response);
return(response);
console.log(test);
'''
How can I keep this running in the background without restarting the python script every time data is needed?
Upvotes: 0
Views: 1521
Reputation: 707696
It seems you need to change the python script itself to keep running and respond to requests from its parent. If the python script now runs and exits, there's nothing you can do from node.js to stop that. You need to change the python script.
Here are some options:
The python script can regularly send data back to its parent on stdout and you can read that data from nodejs as it arrives.
You can put a little local http server or socket.io server in the python script on a known port and have your nodejs parent communicate with that to make requests and get responses.
The Python-shell module also shows you how to communicate between node.js parent and the python script here in the doc, so that is an option too.
Since options 1 and 3 are built-in already, I would probably start with one of those until you find some reason they aren't sufficient.
Upvotes: 1