How to fix "Error: spawn py ENOENT" error when running python script from electron app?

Viewed 4056

I was trying to run some python script from electron app in windows 10.The sample code that I am trying to run is:

let {PythonShell} = require('python-shell')
PythonShell.run('test.py',  function  (err, results)  {
 if  (err)  throw err;
 console.log('test.py finished.');
 console.log('results', results);
});

The code is expected to run test.py which contains a simple print statement.But the terminal shows the following error log:

throw er; // Unhandled 'error' event
      ^

Error: spawn py ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    [... lines matching original stack trace ...]
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
2 Answers

Looks like the Python executable is not available from your node script, which is almost always the case in Windows. Either add the python executable to your PATH variable, or specify the executable path in the options. See constructor options for more details.

Use https://github.com/extrabacon/python-shell#pythonshellscript-options-constructor

Set pythonPath & try.

let options = {
    pythonPath: 'C:\\python27\\python',
  };

  let {PythonShell} = require('python-shell')
  PythonShell.run('test.py', options,  function  (err, results)  {
   if  (err)  throw err;
   console.log('test.py finished.');
   console.log('results', results);
  });

https://github.com/extrabacon/python-shell/issues/3#issuecomment-52174564

For Mac

  1. install python 2.7 from python site.
  2. copy the directory “/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python”
  3. open node modules and 'dmg builder' folder and 'dmg.js' file replace “/usr/bin/python”.

still same error --->

  1. upgrade the electron build "yarn add electron-builder --dev"

I used child process, I'm not sure this will work on python-shell

Related