0

I have this piece of code. It should call my python script if it is true.

The problem is: the script doesn't get executed. I'm using Heroku and I already have nodejs and python in my buildpacks.

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

Note: I already forced the condition to be true and it didn't work. The script was not called

2
  • When you say "doesn't get executed" what happens exactly? Is the code really trying to execute the script, or is currentPhase always different from phaseId? Commented Mar 16, 2020 at 21:01
  • I already forced the condition to be true and it didn't work. The script was not called Commented Mar 16, 2020 at 21:05

1 Answer 1

1

I'm not familiar with python-shell but you can use exec from Node's child_process to run your script

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}`)
    })
  }
}

Running the code:

// 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

add this code for if you want to define currentPhase and phaseId from the command line

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()

from the CLI, you can run

# 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.