I have an api in node js in which I am trying to execute the python Script
My Directory structure is as below
Nodejs_application
index.js
Python_application
script1.py
I just have print("Hello World")
in my script1.py
I have tried the below code in node js to run the python script
const {spawn} = require('child_process');
var dataToSend;
// spawn new child process to call the python script
const python = spawn('python', [__dirname+'../../../../pythoncode/script1.py']);
// collect data from script
python.stdout.on('data', function (data) {
console.log('Pipe data from python script ...');
dataToSend = data.toString();
});
// in close event we are sure that stream from child process is closed
python.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
// send data to browser
res.send(dataToSend)
});
I am getting code 9009
error. Where did I go wrong?
Alternative code which I tried
const {PythonShell} =require('python-shell');
let options = {
mode: 'text',
pythonOptions: ['-u'], // get print results in real-time
// scriptPath: 'path/to/my/scripts', //If you are having python_test.py script in same folder, then it's optional.
// args: ['shubhamk314'] //An argument which can be accessed in the script using sys.argv[1]
};
PythonShell.run('script1.py', options, function (err, result){
if (err) throw err;
// result is an array consisting of messages collected
//during execution of script.
console.log('result: ', result.toString());
res.send(result.toString())
});
Error I am getting is
PythonShellError: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from
Settings > Manage App Execution Aliases.
In CMD I have given "python", I am getting
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.