Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js child_process.spawn is unable to launch python process

I have written following code to spawn a python process. I am able to launch other processes but not python. I tried reinstalling python and node but still no luck. I am able to run python from command line. Please help.

const spawn = require("child_process").spawn;
var process = spawn('python',[ 'D:/python_script.py']);

var responseData = "";

process.stdout.setEncoding('utf-8');
process.stdout.on('data', function (data){
    responseData += data.toString();
});
process.stdout.on('end',function(data){
    console.log(JSON.stringify(responseData));
});

Using node 64 bit v8.2.1

Python script which I am using:

if __name__ == '__main__':
    import sys
    print("Hello")
    f = open('D:/myfile.txt', 'w')
    f.write('hi there\n')  # python will convert \n to os.linesep
    f.close()
    sys.stdout.flush()

Even just spawn('python'); is not launching python window

I have also tried giving absolute path of python.exe.

like image 542
Chandan Kumar Avatar asked May 25 '26 13:05

Chandan Kumar


1 Answers

change

console.log(JSON.stringify(responseData));

to

console.log(responseData);

and add

process.stderr.on('data', function (data){
    responseData += data.toString();
});

below

process.stdout.on('data', function (data){
    responseData += data.toString();
});
like image 110
thomasmeadows Avatar answered May 28 '26 03:05

thomasmeadows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!