简体   繁体   中英

How should I use child_process module to communicate python and node.js in linux?

I'm trying to call python file from node.js. This is the flow/structure: when node.js receives certain value (from frontend via socket) -- run python file (not neccesarily receiving specific input) -- python file will create and save .png file in the same directory.

I tried python-shell in npm modules, but it's keep giving the errors and seems like it wants me to move/copy all imported packages to where that .js file is...

So I'm looking an alternative, and found child_process module. The problem below is that I'm not sure what to put in var pythonExecutable in the code below, since my computer is linux, not windows.

I would appreciate any comment about the methods all above.

I'm referring to this code from https://ourcodeworld.com/articles/read/286/how-to-execute-a-python-script-and-retrieve-output-data-and-errors-in-node-js

// 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 pythonExecutable = "python.exe";

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

// Handle error output
scriptExecution.stderr.on('data', (data) => {
    // As said before, convert the Uint8Array to a readable string.
    console.log(uint8arrayToString(data));
});

scriptExecution.on('exit', (code) => {
    console.log("Process quit with code : " + code);
});
var pythonExecutable = "python"; 

will do. if you use python.exe your telling the process to run the windows .exe command. just "python" will do it will throw an error "python command not found" or similar if python is not install

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM