Skip to content Skip to sidebar Skip to footer

Easy Way to Run Python Scripts From Node Js Application

In this article, I will go through a sample app that can run a python script from Node.js, get data from the script and send it to the browser.

Node.js is one of the most adopted web development technologies but it lacks support for machine learning, deep learning, and artificial intelligence libraries. Luckily, Python supports all these and many more other features. Django Framework for Python can utilize this functionality of Python and can provide support for building new-age web applications using machine learning and Artificial Intelligence.

Those developers who are not familiar with Django Framework but use Node JS framework can also benefit fromPython using child process module for Node JS.

Child Process module for Node JS provides functionality to run scripts or commands in languages other than JavaScript too (like Python). We can implement machine learning algorithms, deep learning algorithms, and many features provided via the Python library into the Node JS application. Child Process allows us to run Python script in Node JS application and stream in/out data into/from Python script.

          child_process.spawn():          This method helps us to spawn child process asynchronously.


Let's create two simple Python scripts one script for execute the script and another pass parameter Node JS to Python script

Python script :

    create script1.pyfile and add code

          print('Hello from python')

   create another script2.py file and add code

          print          (          "Output from Python"          )          print          (          "First name: "          +          sys.argv[          1          ])          print          (          "Last name: "          +          sys.argv[          2          ])        

Run python script

Create a new folder :

mkdir nodePythonScriptApp

Init a new node.js app:

cd nodePythonScriptApp npm init

Install express framework :

npm i express

Finally create the index.js file:

const express = require('express') const { spawn } = require('child_process'); const app = express(); const port = 8812;  app.get('/script1', (req, res) => {     var data1;    // spawn new child process to call the python script    const python = spawn('python3', ['script1.py']);    // collect data from script    python.stdout.on('data', function (data) {       console.log('Pipe data from python script ...');       data1 = data.toString();    });    // in close event we are sure that stream from child process is closed    python.on('close', (code) => {       console.log(`child process close all stdio with code ${code}`);       // send data to browser       res.send(data1)    }); })  app.get('/script2/:fname/:lname', (req, res) => {     var data2;     // spawn new child process to call the python script     const python = spawn('python3', ['script2.py', req.params.fname, req.params.lname]);     // collect data from script     python.stdout.on('data', function (data) {        console.log('Pipe data from python script ...');        data2 = data.toString();     });    // in close event we are sure that stream from child process is closed    python.on('close', (code) => {       console.log(`child process close all stdio with code ${code}`);       // send data to browser       res.send(data2)    }); }) app.listen(port, () => console.log(`node python script app listening on port ${port}!`))        

The above code sets up a basic express app with one get router. Inside the get router, we spawn a new child_process with parameters:

spawn('python', ['script1.py']);  spawn('python', ['script1.py', <here pass parameter to python script>]);        

The first parameter is the program we want to call and the second is an array of strings that will use the python program. It is the same command if you wanted to write it in a shell to run the script1.py

python 'script1.py'  python 'script2.py'

The first event we set is :

python.stdout.on('data', function (data) {   console.log('Pipe data from python script ...');   dataToSend = data.toString();  });

This event is emitted when the script prints something in the console and returns a buffer that collects the output data. In order to convert the buffer data to a readable form, we use data.toString() method .

The last event we set is :

python.on('close', (code) => {  console.log(`child process close all stdio with code ${code}`);  // send data to browser  res.send(dataToSend)  });        

Inside this event, we are ready to send all the data from the python script to the browser.

Run the code :

node index.js/ nodemon index.js        

Thanksyes

smithater1983.blogspot.com

Source: https://www.codesolution.co.in/detail/post/run-python-script-from-nodejs-using-child-process-spawn-method-rest-api

Post a Comment for "Easy Way to Run Python Scripts From Node Js Application"