How to Execute a Python Script in a Node.js Project

This tutorial assumes that you’ve already set up a basic Node.js project with Express. I have other tutorials explaining how to do this if you don’t know how.

First, create a new python file in your Node project directory. I will call mine hello.py. In hello.py, I will write a simple Python print statement to test.

print("Hello world")

In my main JavaScript file, I’m going to add the bolded line:

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

const app = express();

app.get('/', (req, res) => {
   console.log('Hello world');
});

app.listen(4000, console.log('Server started on port 4000'));

In the code above, we set up a basic Express app with one get router. Pay attention to the bolded line:

const { spawn } = require('child_process');

Next, we will use the new spawn class that we imported with this line from the child_process library.

In the get router, add the following lines:

app.get('/', (req, res) => {
   const childPython = spawn('python', ['hello.py']);

   childPython.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`)
   });

   childPython.stderr.on('data', (data) => {
      console.error(`stderr: ${data}`);
   });

   childPython.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
   });
});

In the above code, spawn a new child_process with parameters ‘python‘ and ‘script1.py‘. We set this to an object called childPython:

const childPython = spawn('python', ['hello.py']);

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'

The first event is:

childPython.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`)
 });

The data argument that we are receiving from the callback function will be the output of the Python code we wrote in hello.py. We could also get access to the outputs this way. In the code below, we have to either return or console.log the dataToSend.

python.stdout.on('data', function (data) {
   dataToSend = data.toString();
});

If this event fails, the error event will be called:

childPython.stderr.on('data', (data) => { 
    console.error(`stderr: ${data}`);
});

This is the final event. The close event is emitted (run) when the stdio streams of a child process have been closed:

childPython.on('close', (code) => {
   //res.send(dataToSend)
   console.log(`child process exited with code ${code}`);
});

Here’s another example of a very basic program. This program will generate a random number between 0 and 9 (inclusive):

The contents of num.py file:

import random 

def generate():
    return random.randint(0, 9)

print(generate())

The contents of index.js file:

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

const childPython = spawn('python', ['hello.py']);

childPython.stdout.on('data', (data) => {
    console.log(`The new random number is: ${data}`)
});

childPython.stderr.on('data', (data) => {
    console.error(`There was an error: ${data}`);
});

childPython.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

const app = express();

const PORT = process.env.PORT || 4000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));

The output should look something like this:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s