简体   繁体   English

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

[英]Pass flags to Python Script from Node/Express app python-shell

I am trying to figure out how to pass flags to a python script from a Node/Express application. 我试图弄清楚如何从Node / Express应用程序将标志传递给python脚本。 When in the command line I execute the script by running: 在命令行中,我通过运行以下命令来执行脚本:

python ndbc.py --buoy 46232

I am using the python-shell module, which I think should allow me to do this, but I am not entirely sure how it works. 我正在使用python-shell模块,我认为应该允许我这样做,但我不完全确定它是如何工作的。

python-shell documentation: python-shell文档:

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

Adapted from the README, something like this should work: 改编自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);
});

I found another solution that used the child_process Module: 我找到了另一个使用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);
  }
});

Tested: 测试:

 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'); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM