Nikita Gupta
Nikita Gupta

Reputation: 513

Calling python script with node js express server

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

Upvotes: 6

Views: 12439

Answers (2)

eafloresf
eafloresf

Reputation: 173

If you want to execute it with params

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

Upvotes: 1

MrJLP
MrJLP

Reputation: 998

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

Upvotes: 10

Related Questions