Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PythonShell module in Nodejs

I have been trying to follow the documentation for the npm pythonshell here. I'm just trying to get a simple example to function correctly with no success, not many examples online but I did try to follow this one on stackoverflow. So what exactly is wrong with my code here? I'm not really sure why I'm getting the below error. I'm far more comfortable in python, nodejs is new territory for me. Thank you for any help.

test.py code:

print("This is a test")

Nodejs with pythonshell test:

var PythonShell = require('python-shell');

    var options = {
      mode: 'text',
      pythonPath: '/bin/bash/python2', 
      pythonOptions: ['-u'],
      scriptPath: './TestProject/',
      args: ['value1', 'value2', 'value3']
    };

    PythonShell.run('test.py', options, function (err, results) {
      if (err) throw err;
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });

Here is my error

    internal/child_process.js:313
    throw errnoException(err, 'spawn');
    ^

Error: spawn ENOTDIR
    at exports._errnoException (util.js:1022:11)
    at ChildProcess.spawn (internal/child_process.js:313:11)
    at exports.spawn (child_process.js:387:9)
    at new PythonShell (/home/nomad/TestProject/node_modules/python-shell/index.js:59:25)
    at Function.PythonShell.run (/home/nomad/TestProject/node_modules/python-shell/index.js:159:19)
    at Object.<anonymous> (/home/nomad/TestProject/app.js:11:13)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
like image 992
Machiavelli Avatar asked Dec 21 '16 17:12

Machiavelli


1 Answers

So I made the mistake of not checking my python path on a new system install, however using an absolute path is also nessasary for the script to function. Here is a working example for anyone trying to run python scripts using nodejs python-shell npm. Thanks to Bryan for helping me with javascript error.

var PythonShell = require('python-shell');

    var options = {
      mode: 'text',
      pythonPath: '/usr/bin/python', 
      pythonOptions: ['-u'],
      // make sure you use an absolute path for scriptPath
      scriptPath: '/home/username/Test_Project/Python_Script_dir',
      args: ['value1', 'value2', 'value3']
    };

    PythonShell.run('test.py', options, function (err, results) {
      if (err) throw err;
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });
like image 129
Machiavelli Avatar answered Oct 03 '22 19:10

Machiavelli