NodeJs вызов сценария Python - PullRequest
0 голосов
/ 16 марта 2020

У меня есть этот кусок кода. Он должен вызвать мой python скрипт, если он истинный.

Проблема в том, что скрипт не выполняется. Я использую Heroku, и у меня уже есть 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();
  }
}

Примечание: я уже заставил условие быть верным, и оно не сработало. Сценарий не назывался

1 Ответ

1 голос
/ 17 марта 2020

Я не знаком с python-shell, но вы можете использовать exec из Node's child_process для запуска вашего скрипта

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)

CLI

добавьте этот код, если вы хотите определить currentPhase и phaseId из командной строки

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...