简体   繁体   中英

How to run Python Script from node js

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.

seems like you are not providing the correct python path and python is not configured on your path and hence not recognized as 'python'.

take a look at:

  • C:\Python36
  • C:\Users(Your logged in User)\AppData\Local\Programs\Python\Python36

or try running:

where python

in order to get full path.

additionally i would recommend you to use a package for running your script.

you can check this package on npm- native-python

it provides a very simple and powerful way to run python functions from node might solve your problem. import { runFunction } from '@guydev/native-python'

const example = async () => {
   const input = [1,[1,2,3],{'foo':'bar'}]
   const { error, data } = await runFunction('/path/to/file.py','hello_world', '/path/to/python', input)

   // error will be null if no error occured.
   if (error) {
       console.log('Error: ', error)
   }

   else {
       console.log('Success: ', data)
       // prints data or null if function has no return value
   }
}

python module

# module: file.py

def hello_world(a,b,c):
    print( type(a), a) 
    # <class 'int'>, 1

    print(type(b),b)
    # <class 'list'>, [1,2,3]

    print(type(c),c)
    # <class 'dict'>, {'foo':'bar'}

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