【问题标题】:NodeJs call a Python scriptNodeJs 调用 Python 脚本
【发布时间】:2020-03-23 23:49:28
【问题描述】:

我有这段代码。如果它是真的,它应该调用我的 python 脚本。

问题是:脚本没有被执行。我正在使用 Heroku,并且我的 buildpack 中已经有了 nodejs 和 python。

const express = require('express');
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

let {PythonShell} = require('python-shell');
app.post('/api/apipath', (req, res) => {
  if (currentPhase == phaseId){
    PythonShell.run('./src/main.py', null, function (err){
      if (err) throw err;
      console.log('Finish');
    });
    res.end();
  }else{
    res.end();
  }
}

注意:我已经强制条件为真,但它不起作用。脚本没有被调用

【问题讨论】:

  • 当你说“没有被执行”时,究竟发生了什么?代码是否真的在尝试执行脚本,或者currentPhase 总是与phaseId 不同?
  • 我已经强制条件为真,但它不起作用。该脚本未被调用

标签: python node.js heroku


【解决方案1】:

我不熟悉python-shell,但您可以使用 Node 的 child_process 中的 exec 来运行您的脚本

const { exec } = require('child_process')

function runPythonScript(script, runFile = false) {
  console.log(`Run? ${runFile}`)

  if (runFile) {
    exec(`python ${script}`, (error, stdout, stderr) => {
      if (error) {
        console.error(`exec error: ${error}`)
        return
      }
      console.log(`stdout: ${stdout}`)
      console.error(`stderr: ${stderr}`)
    })
  }
}

运行代码:

// this will run
runPythonScript('./src/main.py', 1 === 1)

// this will not run
runPythonScript('./src/main.py', 0)

// this will run since both currentPhase and phaseId are empty variables 
var currentPhase, phaseId
runPythonScript('./src/main.py', currentPhase === phaseId)

命令行

如果您想从命令行定义currentPhasephaseId,请添加此代码

function init() {
  const [, , ...args] = process.argv

  var currentPhase, phaseId
  currentPhase = args[args.indexOf('--currentPhase') - 1]
  phaseId = args[args.indexOf('--phaseId') - 1]

  runPythonScript('./program.py', currentPhase === phaseId)

}
init()

从 CLI,您可以运行

# sets currentPhase to 99 and phaseId as 98 (does not run)
node lib/filename-to-runPythonScript.js 99 --currentPhase 98 --phaseId

# sets both currentPhase and phaseId to 123 (does run)
node lib/filename-to-runPythonScript.js 123 --currentPhase 123 --phaseId

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2018-03-25
    相关资源
    最近更新 更多