Run Python Script using PythonShell from Node.js
Last Updated :
19 Nov, 2021
Nowadays Node.js is the most attractive technology in the field of backend development for developers around the globe. And if someone wishes to use something like Web Scraping using python modules or run some python scripts having some machine learning algorithms, then one need to know how to integrate these two.
We are going to get some data of a user through web scraping of leetcode . So, let’s get started.
Now, setup the Node.js server code first.
JavaScript
//Import express.js module and create its variable.
const express=require('express');
const app=express();
//Import PythonShell module.
const {PythonShell} =require('python-shell');
//Router to handle the incoming request.
app.get("/", (req, res, next)=>{
//Here are the option object in which arguments can be passed for the python_test.js.
let options = {
mode: 'text',
pythonOptions: ['-u'], // get print results in real-time
scriptPath: 'path/to/my/scripts', //If you are having python_test.py script in same folder, then it's optional.
args: ['shubhamk314'] //An argument which can be accessed in the script using sys.argv[1]
};
PythonShell.run('python_test.py', options, function (err, result){
if (err) throw err;
// result is an array consisting of messages collected
//during execution of script.
console.log('result: ', result.toString());
res.send(result.toString())
});
});
//Creates the server on default port 8000 and can be accessed through localhost:8000
const port=8000;
app.listen(port, ()=>console.log(`Server connected to ${port}`));
Now, Python Script. (Make sure you have installed the bs4 module and csv module.)
Python3
# code
import sys
import requests
from bs4 import BeautifulSoup
from csv import writer
# bs4 module for web scraping and requests for making HTTPS requests using Python.
response = requests.get('https://leetcode.com / shubhamk314')
soup = BeautifulSoup(response.text, 'html.parser')
main_content = soup.select(
'# base_content>div>div>div.col-sm-5.col-md-4>div:nth-child(3)>ul')
list_items = main_content[0].select('li')
items = ['Solved Question', 'Accepted Submission', 'Acceptance Rate']
n = 0
# It will create csv files named progress.csv in root folder once this is script is called.
with open('progress.csv', 'w') as csv_file:
csv_writer = writer(csv_file)
headers = ['Name', 'Score']
csv_writer.writerow(headers)
while(n < 3):
name = items[n]
score = list_items[n].find('span').get_text().strip()
csv_writer.writerow([name, score])
n = n + 1
print("csv file created for leetcode")
After saving both the files, run the following command from its root folder :
node test.js
Now, send request through localhost:8000 in the browser.
If everything goes right, then the output will be :
Message: csv file created for leetcode.

Conclusion
This is the simple implementation of a how-to run python script with Node.js which can be useful in situations where you have a stack of Node.js application and you want to run a simple python script. If you want to know more about PythonShell module, then go through the given link.
Link : https://github.com/extrabacon/python-shell
Similar Reads
Run Python script from Node.js using child process spawn() method 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 ca
3 min read
How to Run a Python Script using Docker? Docker helps you to run your Python application very smoothly in different environments without worrying about underlying platforms. Once you build an image using dockerfile you can run that image wherever you want to run. Docker image will help you to package all the dependencies required for the a
8 min read
How to run bash script in Python? If you are using any major operating system, you are indirectly interacting with bash. If you are running Ubuntu, Linux Mint, or any other Linux distribution, you are interacting with bash every time you use the terminal. Suppose you have written your bash script that needs to be invoked from python
2 min read
How to Run a Python Script Python scripts are Python code files saved with a .py extension. You can run these files on any device if it has Python installed on it. They are very versatile programs and can perform a variety of tasks like data analysis, web development, etc. You might get these Python scripts if you are a begin
6 min read
Run python script from anywhere in linux In Linux, there is a way to execute python files from anywhere. This can be done by typing several commands in the terminal. Prerequisite: Basic Shell Commands in Linux Basics of python Steps: At first, open the terminal and go to the home directory. To go the home directory type the following comma
2 min read