Sitemap
Dushan Senadheera

Dushan Senadheera

Associate Software Engineer @Fortude | Graduate @University of Plymouth, UK

Run Python script using NodeJS

2 min readOct 23, 2023
Press enter or click to view image in full size

Node.js is a versatile platform for building server-side applications, but sometimes you may need to incorporate other programming languages into your Node.js applications. One common use case is running Python scripts within a Node.js application. This can be achieved using the child process module in Node.js. In this article, we will explore how to run a simple Python script to calculate the total of given two numbers using the NodeJS child process.

  1. Inside your project directory initialize a new Node.js project with the following command
npm init -y

2. Next, create a JavaScript file (e.g., index.js) with the following content where you will use the child process to run the Python script.

Get Dushan Senadheera’s stories in your inbox

Join Medium for free to get updates from this writer.

the example below shows a sample node.js application with express.js

const express = require('express')
const { spawn } = require('child_process');
const app = express()
const port = 3000

app.get('/', (req, res) => {

const firstNum = 4;
const secondNum = 7;

let dataToSend;
// spawn new child process to call the python script
// and pass the variable values to the python script
const python = spawn('python', ['script.py', firstNum , secondNum]);
// collect data from script
python.stdout.on('data', function (data) {
console.log('Pipe data from python script ...');
dataToSend = 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(dataToSend)
});

})

app.listen(port, () => {
console.log(`app is listening on port ${port}!`)
})

3. Create a Python script in the same directory. For example, you can create a script named script.py with the following content.

# import system library
import sys

# take passed variable values
first_num = int(sys.argv[1])
second_num = int(sys.argv[2])

# calcluate the total using variable values and print the output
def calculate_total(first_num , second_num ):
print(first_num + second_num )

# call the function and pass variables to it
calculate_total(first_num , second_num )

4. Run the Node.js application using the following command.

node index.js

This approach is particularly useful when integrating existing Python scripts or leveraging Python’s capabilities in your Node.js projects. With the child process module, you can execute Python scripts and seamlessly capture their output or errors.

Please find the full source code for this sample application here

--

--

Dushan Senadheera
Dushan Senadheera

Written by Dushan Senadheera

Associate Software Engineer @Fortude | Graduate @University of Plymouth, UK