0

I am using a node server to run python scripts. I am using the Python shell package to run them and this works fine. Here it is in the server.js file that I am running:

app.get('/start/:fileName', function(req, res) {  
  let fileName = req.params.fileName;
  console.log(fileName)
  PythonShell.run(`./python_scripts/${fileName}`, function (err,results) {
    console.log('results ',results);
    if (err) throw err;
    console.log('finished');
  });
});

In another file main.js I have the command:

function fetchStartEndpoint(fileName) {
  fetch(`/start/${fileName}`)
    .catch(error => console.log(error));
}``

And I call fetchStartEndpoint when a button is clicked.

This all works fine but I want to use multiple buttons to run multiple scripts. When I click the button a script runs, but when I click a different button to run a different script, the first one continues to run. I want it to end and run the second one. Is there a way to override the initial script and run the second one instead of other than restarting the server?

1 Answer 1

1

I'm quickly browsing the readme at python-shell and it seems to me that calling end on the shell instance is the way to stop the running script:

run(script, options, callback)

This method is also returning the PythonShell instance.

.end(callback)

Closes the stdin stream, allowing the Python script to finish and exit. The optional callback is invoked when the process is terminated.

Based on that I would assume this can work:

// First button pressed ... 
var shell = PythonShell.run('script.py', function (err, results) {
   // script finished 
   shell = null
});

// Second button pressed ... 
if (shell) {

    shell.end(function() {
       // start second script ...
    })
}
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.