Calling Python Script from NodeJs Code

Learn to call a python script from node.js in this post.

Python script

Here is a simple python script that receives one argument and prints the same. Before printing out any data we can perform the a function.

import sys

firstArgument = sys.argv[1]

# do something here

print(firstArgument)

sys.stdout.flush()
Python script - index.py

Node.js script

Here is a Node.js script that calls the python script.

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

const pythonFile = 'index.py';

const pythonProcess = spawn('python', [pythonFile, 'arg1']);

pythonProcess.stdout.on('data', function(data) {
    console.log(data.toString());
});

pythonProcess.stderr.on('data', (data) => {
    console.log(data.toString());
});

pythonProcess.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});
Node.js script - call-python.js

The example usages node.js child_process.spawn method. This method spawns a process with the given command. The provided command must be installed like to run above example python command should be installed on the system.

The child_process is an inbuilt module of Node.js. Using this module, you can create child processes. The child process communicates through pipe methods like stdout, stderr with the parent process.