7

With below code I have created a HTTP server on port 3000 and have added some get parameters. I want to invoke a python script with this express.js server code such that when I hit localhost:3000/key1/abc/key2/234 python script will get invoked. I've my python script ready which takes input args as sys.argv. Please suggest how to call python script with this code so that it will take value1 and value 2 as input arguments and return json.

var express = require('express');
var app = express();
app.get('/key1/:value1/key2/:value2',function(req,res)
{
    console.log(req.params);
    var value1 = req.params.value1;
    var value2 = req.params.value2;
    res.send(req.params);
});
app.listen(3000,function()
{
    console.log("Server listening on port 3000");
});

2 Answers 2

10

To run a Python script from Node.js would require spawning a new process. You can do that with child_process.

You would run python as the executable and give your script name as the first argument.

Here is an example based on the documentation linked above:

const spawn = require('child_process').spawn;
const ls = spawn('python', ['script.py', 'arg1', 'arg2']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});
Sign up to request clarification or add additional context in comments.

3 Comments

and how to pass the parameters so that python program can accept it as sys.argv and return a json
var arg1 = req.params.value1; var arg2 = req.params.value2; const ls = spawn('python', ['script.py', arg1, arg2]); Is this correct?
upvoted but what do I do if I want an infinite python process running and express needs to communicate with that
1

If you want to execute it with params

const scriptExecution = spawn(pythonExecutable, ["my_Script.py", "Argument 1","Argument 2"]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.