簡體   English   中英

從Node / Express應用程序python-shell將標志傳遞給Python腳本

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

我試圖弄清楚如何從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

改編自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);
});

我找到了另一個使用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);
  }
});

測試:

 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