Search code examples
node.jsspawnenoent

spawn python ENOENT node.js in windows


I created some code to use a python function from a node.js backend. When running it on my ubuntu computer, it works - however! When running the code on his windows machine it gives this stacktrace.

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: spawn python 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:757:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622: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:622:3)

This is the node.js file

const spawn = require("child_process").spawn;
const pythonProcess = exec('python',["./script.py", 2, 4]);

pythonProcess.stdout.on('data', function(data) {
    console.log(data.toString('utf-8'))
} )

and this is the script.py file

import sys

print("work with me please")
sys.stdout.flush()

There is a ton of people with issues like this, however all the answers seem to be over specific for the particular person. Some mentions path variables, some npm.cmd and others something else entirely.

How should I work around this particular case?

I have tried npm init, npm install, moving pieces of code around, googling and changed scope of cmd and directory and so on.


Solution

  • Hey i had a similar problem and this did the trick , it was fixed when i added pythonPath: 'python' :

    const { PythonShell } = require('python-shell');
    
    let options = {
        mode: 'text',
        pythonPath: 'python',
        pythonOptions: ['-u'], // get print results in real-time
        scriptPath: 'path',
        args: ['arg1', 'arg2']
    };
    
    PythonShell.run('scraper.py', options, function(err, results) {
        if (err) console.log(err);
        // results is an array consisting of messages collected during execution
        console.log('results: %j', results);
    });