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

狂风中的少年 提交于 2021-01-27 18:44:24

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/45318802/node-js-child-process-spawn-is-unable-to-launch-python-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!