Search code examples
node.jsnpmjs

python-shell from a node application


Question:

How do I run my python script in my node app?

This works:

From command line, I run this, and it works.

python generatePersonTerraform.py -s http://localhost:8080/api/person/239/exportPersonGeneration

Code that does not work in Node server.js

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

var runPythonRoutine = function (request, response) {
    var PythonShell = require('python-shell');
    var options = {
        mode: 'text',
        pythonPath: 'python',
        pythonOptions: ['-s'],
        scriptPath: '.',
        args: ['http://localhost:8080/api/person/135/exportPersonGeneration']
    };
    PythonShell.run('generatePersonTerraform.py', options, function (err, results) {
       console.log(err);
    });
}

Error:

    at PythonShell.parseError (/root/my-app/node_modules/python-shell/index.js:191:17)
    at terminateIfNeeded (/root/my-app/node_modules/python-shell/index.js:98:28)
    at ChildProcess.<anonymous> (/root/my-app/node_modules/python-shell/index.js:89:9)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:194:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
  executable: 'python',
  options: [ '-s' ],
  script: 'generatePersonTerraform.py',
  args: [ 'http://localhost:8080/api/person/239/exportPersonGeneration' ],
  exitCode: 1 }

Note

I have been trying to use https://www.npmjs.com/package/python-shell

EDIT 1

I changed the options to:

var options = {
    mode: 'text',
    pythonPath: 'python',
    pythonOptions: [],
    scriptPath: '.',
    args: ['-s', 'http://localhost:8080/api/serviceType/135/exportPluginGeneration']
};

and got this error:

    at PythonShell.parseError (/root/my-app/node_modules/python-shell/index.js:191:17)
    at terminateIfNeeded (/root/my-app/node_modules/python-shell/index.js:98:28)
    at ChildProcess.<anonymous> (/root/my-app/node_modules/python-shell/index.js:89:9)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:194:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
  executable: 'python',
  options: null,
  script: 'generatePersonTerraform.py',
  args: 
   [ '-s',
     'http://localhost:8080/api/person/135/exportPersonGeneration' ],
  exitCode: 0 }

But, it also ran and worked, it just stalls the node app. So, if I figure out how to make it not stall then I am all good. The python script seems to build all the files it is supposed to.


Solution

  • '-s' should be in args, not pythonOptions.