Amit Naik
Amit Naik

Reputation: 121

Spawning child process in python in Node JS

I have written the following code in app.js for Windows

app.js

app.route('/file').post(function (req,res,next) {
// The path to your python script
var myPythonScript = "script.py";
// Provide the path of the python executable, if python is available as environment variable then you can use only "python"
var path =resolve("C:\\Python27\\python.exe");
var pythonExecutable = path;
var macadd =req.body.macadd;
var percent =req.body.percent;
// Function to convert an Uint8Array to a string
var uint8arrayToString = function(data){
    return String.fromCharCode.apply(null, data);
};

const spawn = require('child_process').spawn;
const scriptExecution = spawn(pythonExecutable, [myPythonScript]);

// Handle normal output
scriptExecution.stdout.on('data', (data) => {
    console.log(String.fromCharCode.apply(null, data));
});
var data = JSON.stringify([1,2,3,4,5]);
scriptExecution.stdin.write(data);
// End data write
scriptExecution.stdin.end();
});

As you can see the path for the python executable file is provided. This code works properly in Windows and gives the summation of the number in the array on the console. I want to execute the same code in Ubuntu. What do I specify for the python executable path in Linux(Ubuntu)?

Upvotes: 3

Views: 1083

Answers (2)

peiiion
peiiion

Reputation: 298

That will depend on where is the python executable in your Linux setup.

As you said it's an Ubuntu (no version specified), you can try just using python without a path, as the python executable should be already in the PATH and usually it comes installed with your distribution.

If that doesn't work, you can figure out the python executable path running which python on the Linux shell.

And lastly, you can also try /usr/bin/python for the executable path, as it's the usual location for it.

Upvotes: 1

NBeydon
NBeydon

Reputation: 703

You can use process.platform to get the current platform. For example on my mac I have process.platform === 'darwin'. documentation

Upvotes: 0

Related Questions