Node.js Tutorial to Run Python Scripts Using Python-Shell Library in Javascript Full Tutorial For Beginners

 

 

npm i python-shell

 

 

 

import {PythonShell} from 'python-shell';

PythonShell.runString('x=1+1;print(x)', null, function (err) {
  if (err) throw err;
  console.log('finished');
});

 

 

Or you can use require like so:

let {PythonShell} = require('python-shell')

Running a Python script:

import {PythonShell} from 'python-shell';

PythonShell.run('my_script.py', null, function (err) {
  if (err) throw err;
  console.log('finished');
});

If the script exits with a non-zero code, an error will be thrown.

Running a Python script with arguments and options:

import {PythonShell} from 'python-shell';

let options = {
  mode: 'text',
  pythonPath: 'path/to/python',
  pythonOptions: ['-u'], // get print results in real-time
  scriptPath: 'path/to/my/scripts',
  args: ['value1', 'value2', 'value3']
};

PythonShell.run('my_script.py', options, function (err, results) {
  if (err) throw err;
  // results is an array consisting of messages collected during execution
  console.log('results: %j', results);
});

Exchanging data between Node and Python:

import {PythonShell} from 'python-shell';
let pyshell = new PythonShell('my_script.py');

// sends a message to the Python script via stdin
pyshell.send('hello');

pyshell.on('message', function (message) {
  // received a message sent from the Python script (a simple "print" statement)
  console.log(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');
});

Leave a Reply