How to run Python directly from Javascript

Estimated reading time: 3 minutes

Are you developing a website and looking to execute some Python script directly from the website?

Here we take you through how to achieve this using Python Flask, the scenarios we demonstrate are as follows:

  1. Javascript on load event – execute Python script
  2. Javascript on click event – execute a Python script

In both scenarios above you will be presented with pop-up boxes like below, but the python code can be changed to whatever you like.

Page load message box
On button press, calls the python script to load a message box

The code you will need to run this is split into two. (A) The Index.HTML logic and (B) the logic

The code for the INDEX.HTML page

This is the page that the user is presented with. As you can see the logic has two pieces of javascript that when run, go over to the python code and run some logic that it wishes the webpage to run.

In this instance, the python script holds the commands that need to be executed.

Note the page load event goes to the route in, namely ” @app.route(‘/’)”

Whereas the button click event is pointed directly at “@app.route(‘/test’ )” – essentially this will not run until the javascript asks it to, on the button click event.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Sample Home Page</title>
<! -- Calls a function on the page load. -- >
<element onload="myfunction_onload">
<button type="submit" onclick='myfunction_clickevent()'>Run my Python!</button>
<script type="text/javascript" src=""></script>
<! -- This script runs the python script on the page load -->
    function myfunction_onload(){
            url: "",
             context: document.body
<! -- This script runs the python script when the button is clicked -->
    function myfunction_clickevent(){
            context: document.body});}

How to run Python directly from Javascript

The code for the APP.PY Python script

Here we are linking to the index.html page and taking commands from it and executing those requests.

In this scenario, the message boxes are rendered by using the win32api package.

The app is using the flask package to run the website.

The powerful thing here is you can start customising this logic to do what you like, examples include:

(A) Return graphs to the webpage.

(B) Process data received and return statistics on the data.

(C) Validate data received in Python and return a response. An example here could be a user logging into a database.

import win32api
from flask import Flask, render_template

app = Flask(__name__)

#Using the below, the popup message appears on the page load of index.html
#0x00001000 - This makes the popup appear over the browser window
def index():
    win32api.MessageBox(0, 'You have just run a python script on the page load!', 'Running a Python Script via Javascript', 0x00001000)
    return render_template('index.html')

#Using the below, the popup message appears when the button is clicked on the webpage.
#0x00001000 - This makes the popup appear over the browser window
def test():
    win32api.MessageBox(0, 'You have just run a python script on the button press!', 'Running a Python Script via Javascript', 0x00001000)
    return render_template('index.html')

if __name__ == "__main__":

How to Pass a Javascript Variable to Python using JSON

Estimated reading time: 4 minutes

So you have an application or website that is capturing data using javascript, and you want to pass this to Python, so you can process it further.

Here using Flask, Python’s package for web development, we will show you how to achieve this, and also explain the JSON output.

Where could this be useful?

(A) You want to pass data to a Python program to run a Machine Learning program you have written.

(B) You want to use Pythons functionality to add the data to a dashboard in real-time.

(C) Another use could be that you are in real-time processing requests on a website, but also want to use Python’s functionality to capture metrics on the data.

So how do we achieve this?

Step 1 – In Python create a Flask application

When you create a new Python file, the first step is to create add your import statements to the top of the file:

import json

from flask import request

from flask import Flask, render_template

app = Flask(__name__)

As can be seen from the above, we bring in the flask package. This is now starting the process of creating a web development site.

Step 2 – Create the web route for telling the programme what the HTML template is called.

def index():
return render_template('index.html')

Step 3 – Create the logic that will receive the data from the JSON on the website.

@app.route('/test', methods=['POST'])
def test():
    output = request.get_json()
    print(output) # This is the output that was stored in the JSON within the browser
    result = json.loads(output) #this converts the json output to a python dictionary
    print(result) # Printing the new dictionary
    print(type(result))#this shows the json converted as a python dictionary
    return result

In the above we will explain the logic:

/test ===> this is what the page further on the logic will look to send the data entered on the website to.

methods=[‘POST’] ===> This is what it is looking out for when the JSON is been sent.

As can be seen in the function the rest of the code just retrieves the data and processes it.

Step 4 – Create the HTML file that will capture input and process the data to JSON.

So the main part of this program is loading the HTML file, entering the data onto the page and then processing it with javascript and AJAX.

The page looks like this:

The code behind this is as follows:

<html lang="en">


    <title>Data Analytics Ireland</title></head>

<P>Post some values to a json file</P>

<label for="fname">First name:</label> <input type="text" id="fname" name="fname">
<label for="lname">Last name:</label><input type="text" id="lname" name="lname">
<button type="submit" onclick='myfunction();'>Click Here to see your data</button>

<script type="text/javascript" src=""></script>
    function myfunction() {

        const firstname = document.getElementById("fname").value;
        const lastname = document.getElementById("lname").value;

        const dict_values = {firstname, lastname} //Pass the javascript variables to a dictionary.
        const s = JSON.stringify(dict_values); // Stringify converts a JavaScript object or value to a JSON string
        console.log(s); // Prints the variables to console window, which are in the JSON format
            contentType: "application/json",
            data: JSON.stringify(s)});




This block of code is HTML and runs as follows:

There are two input text boxes that take the data entered.

There is a button that when clicked, runs the function onclick=’myfunction();’

Within this function, the const firstname and const lastname capture the values entered into the boxes using the javascript document.getElementById

We then create a dictionary with those values.

Next, we create a variable that takes the dictionary and converts it into the JSON format.

The section starting with ” $.ajax“, creates the JSON and readies it to be passed to “/test” identified in step3.

STEP 5 – Where does this leave us?

At this point, if the program is run and the data has been entered, and the button is clicked, the data has been captured by the javascript, passed into the dictionary and converted to JSON format.

So what does this all look like when completed?

Data entered:

Printed output:

The data first comes as JSON str and is then converted to a Python dictionary.

After this, you can then start manipulating the data in Python!