1

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.
jabaa
  • 5,844
  • 3
  • 9
  • 30
  • Is this a Windows system? – jabaa Feb 24 '22 at 14:54
  • @jabaa Yes it is a windows system – Rajitha Ganji IN Feb 24 '22 at 14:55
  • Do you use CMD or PowerShell? 9009 is the CMD error code for "command not found": [Official MS reference for cmd.exe %errorlevel% 9009](https://stackoverflow.com/questions/23091906/official-ms-reference-for-cmd-exe-errorlevel-9009) Can you start Python with `python` in your CMD? Did you set the path in your environment variables? – jabaa Feb 24 '22 at 14:59
  • I use CMD. What is the command missing – Rajitha Ganji IN Feb 24 '22 at 15:03
  • What happens when you open a new CMD window and type `python`? Do you get the error message `'python' is not recognized as an internal or external command, operable program or batch file.` or do you get a Python REPL? Did you set the path to the Python executable in your environment variables? – jabaa Feb 24 '22 at 15:04
  • No I didnt set in environment variables. How to set it?. Actually I have zero knowledge on python. And 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." – Rajitha Ganji IN Feb 24 '22 at 15:10
  • It seems like the Python path is already set. I can't help here. I have no Windows system at hand and no experience with this. – jabaa Feb 24 '22 at 15:12
  • I have edited my question I tried with "python-shell", even that is giving me error which I have shared in the question – Rajitha Ganji IN Feb 24 '22 at 15:14
  • @RajithaGanjiIN Have you python installed?! What does `python --version` output? – Marc Feb 24 '22 at 15:15
  • @Marc Python 3.10.0 is installed. It was in a comment. I added it to the question. – jabaa Feb 24 '22 at 15:17
  • The only two options I could think of are, 1) the Python path is not set in your environment variables (can you start it from everywhere?) and 2) your environment variables aren't read by `spawn` call. – jabaa Feb 24 '22 at 15:20
  • I dont access to see the environmental variable is there a way to give the path from code? – Rajitha Ganji IN Feb 24 '22 at 15:28
  • 1
    Of course, you can set full path. Replace `spawn('python'` with `spawn('Z:\full\path\to\bin\python'` – jabaa Feb 24 '22 at 15:29
  • @jabaa I tried with the path, I am getting the error as "ganji002AppDataLocalProgramsPythonPython310 ENOENT". Why is my path getting displayed without backslash in the error – Rajitha Ganji IN Feb 24 '22 at 15:54
  • You need double backslashes `\\ ` or slashes `/` – jabaa Feb 24 '22 at 15:58
  • It is giving me the same ENOENT errno:-4058 for the path "C:/Users/rrrr002/AppData/Local/Programs/Python/Python310" – Rajitha Ganji IN Feb 24 '22 at 16:19
  • Do you have a file `C:/Users/rrrr002/AppData/Local/Programs/Python/Python310` without extension? What is the result of `dir C:/Users/rrrr002/AppData/Local/Programs/Python/Python310`? – jabaa Feb 24 '22 at 16:33
  • @jabaa I didnt understand, what do you mean by without extension? – Rajitha Ganji IN Feb 24 '22 at 17:34
  • @jabaa I have python.exe and pythonw.exe inside "C:/Users/rrrr002/AppData/Local/Programs/Python/Python310" – Rajitha Ganji IN Feb 24 '22 at 17:37
  • Why did you call `C:/Users/rrrr002/AppData/Local/Programs/Python/Python310` then? You can't run a directory. You have to run an executable. – jabaa Feb 24 '22 at 17:40
  • @jabaa So I have to call "C:/Users/rrrr002/AppData/Local/Programs/Python/Python310/python.exe"? – Rajitha Ganji IN Feb 24 '22 at 17:44
  • Why didn't you try it instead of asking? – jabaa Feb 24 '22 at 17:48
  • @jabaa I have tried it, its working. Thanks alot. – Rajitha Ganji IN Feb 24 '22 at 17:57
  • Why do you use `'../pythoncode/script1.py'` instead of `"C:\IWA\local\project\pythoncode\script1.py"`? – jabaa Feb 24 '22 at 18:19
  • @jabaa because the path of the python script is specific to the node directory, and not specific fo the drive – Rajitha Ganji IN Mar 02 '22 at 15:32
  • @jabaa Do you have idea of streams? if so can you help with this https://stackoverflow.com/questions/71324909/read-mth-row-to-nth-row-from-a-buffer-data-in-node-js – Rajitha Ganji IN Mar 02 '22 at 15:33
  • @jabaa I tried the above code in different environment. It is giving me the error Requirement already satisfied: pandas in c:\programdata\anaconda3\lib\site-packages (1.4.1) Requirement already satisfied: python-dateutil>=2.8.1 in c:\programdata\anaconda3\lib\site-packages (from pandas) (2.8.2) Requirement already satisfied: numpy>=1.18.5 in c:\programdata\anaconda3\lib\site-packages (from pandas) (1.20.3) Requirement already satisfied: pytz>=2020.1 in c:\programdata\anaconda3\lib\site-packages (from pandas) (2021.3) – Rajitha Ganji IN Mar 04 '22 at 11:30
  • When I try to install pandas it is givng me the above error. But in nodejs it is giving import pandas as pd ModuleNotFoundError: No module named 'pandas' – Rajitha Ganji IN Mar 04 '22 at 11:32
  • Anaconda has its own Python executable and libraries. `C:/Users/rrrr002/AppData/Local/Programs/Python/Python310/python.exe` doesn't use `c:\programdata\anaconda3\lib\site-packages`. Either use the Python executable from Anaconda or install pandas for the other Python installation. – jabaa Mar 04 '22 at 11:54

1 Answers1

0

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'}
Guy-dev
  • 21
  • 4
  • 1
    It looks like you are promoting your own work. [Please see the instructions on self-promotion](https://stackoverflow.com/help/promotion): "_you **must** disclose your affiliation in your post._" – starball Dec 11 '22 at 20:51