从Node / Express应用程序python-shell将标志传递给Python脚本

时间:2016-04-19 18:16:12

标签: javascript python node.js express

我试图弄清楚如何从Node / Express应用程序将标志传递给python脚本。在命令行中,我通过运行:

来执行脚本
python ndbc.py --buoy 46232

我正在使用python-shell模块,我认为应该允许我这样做,但我不完全确定它是如何工作的。

python-shell文档:

https://github.com/extrabacon/python-shell#running-a-python-script-with-arguments-and-options

3 个答案:

答案 0 :(得分:2)

改编自README,这样的东西应该起作用:

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

var options = {
  args: ['--buoy', '46232']
};

PythonShell.run('ndbc.py', options, function (err, results) {
  if (err) throw err;
  console.log('results: %j', results);
});

答案 1 :(得分:1)

我找到了另一个使用child_process模块​​的解决方案:

var exec = require('child_process').exec;
var pyArgs = {
  // make arguments that take no parameters (ie, --json) true or false
  "buoy": '46232',
  "datasource": 'http',
  "json": true,
  "datatype": "spectra",
  "units": 'ft'
};
//example
pyArgs.datatype = '9band';

function flagGen(args) {
  var flags = '';
  for (var a in args) {
    if (args.hasOwnProperty(a)) {
      if (typeof(pyArgs[a]) == 'string'){
        flags += " --" + a + ' ' + pyArgs[a];
      }
      else {
        if (pyArgs[a] == true)
          flags += ' --' + a;
      }
    }
  }
  return flags;
}

var pyPath = './';
var buoyData = ''
var execstr = 'python ' + path.join(pyPath, 'ndbc.py') + flagGen(pyArgs);
var child = exec(execstr, function(error, stdout, stderr) {
  if (error) {
    console.log(stderr)
  }
  else {
    buoyData= JSON.parse(stdout);
    console.log(buoyData);
  }
});

答案 2 :(得分:0)

已测试:

const PyShell = require("python-shell");

let options = {
    mode: 'text',
    pythonPath: 'your_python_path',
    pythonOptions: ['-u'], // get print results in real-time
    args: ['-p {"a":1, "b":"123"}']
};

let pyshell = new PyShell.PythonShell('your_script_path', options);

pyshell.on('message', function(message) {
    // received a message sent from the Python script (a simple "print" statement)
    console.log("Received", message);
});

// end the input stream and allow the process to exit
pyshell.end(function(err, code, signal) {
    if (err) throw err;
    console.log('The exit code was: ' + code);
    console.log('The exit signal was: ' + signal);
    console.log('finished');
});