Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • TypeError: the first argument must be callable Python
  • R – How to open a file R Programming
  • How can I filter my data in Tableau? data visualisation
  • ValueError: pattern contains no capture groups Value Error
  • What are measures in Tableau? data visualisation
  • R – How to check a file exists and is not empty R Programming
  • TypeError: ‘str’ object is not callable Python Functions
  • What are dimensions in Tableau? data visualisation

How to run Python directly from Javascript

Posted on February 14, 2022January 23, 2023 By admin 4 Comments on 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 app.py 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 app.py python script holds the commands that need to be executed.

Note the page load event goes to the route in app.py, 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">
<head>
    <meta charset="UTF-8">
    <title>Sample Home Page</title>
</head>
<body>
<! -- 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="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<! -- This script runs the python script on the page load -->
<script>
    function myfunction_onload(){
        $.ajax({
            url: "app.py",
             context: document.body
            })
        }
    </script>
<! -- This script runs the python script when the button is clicked -->
<script>
    function myfunction_clickevent(){
        $.ajax({
            url:"/test",
            context: document.body});}
</script>


</body>
</html>
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
@app.route('/')
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
@app.route('/test')
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__":
    app.run(debug=True)
Flask, Javascript, Python Tags:ajax, Data Analysis, javascript, Python, python flask

Post navigation

Previous Post: What Is An Array In Python?
Next Post: How to pass multiple lists to a function and compare

Related Posts

  • Python Overview Interview Questions automation
  • Python tutorial: Create an input box in Tkinter Python
  • create read update delete using Tkinter class
  • Tkinter python tutorial Python
  • How to Generate Random Integers Between 0 and 9 Python
  • TypeError: ‘float’ object is not callable Python

Comments (4) on “How to run Python directly from Javascript”

  1. Barbara says:
    December 13, 2022 at 11:37 pm

    Dear Sir,

    I am new to Python and web programming. I do have some programming experience but would not call myself an expert.

    I am afraid I don’t seem to be able to make this run. I don’t get any errors when loading the webpage. It just doesn’t do anything when loading or when clicking the button. Apart from watching your video two times and reading the text, here is what I did and tried.

    System: Windows11, Python 3.11.1, Browser Firefox 108.0
    I made sure I have the necessary python packages and when putting the import lines in different (working) python code it does not throw an error when running it. Internet connection was stable during working.

    I made a 1:1 copy of the code you posted, put the html code in a file index.html and the python code in a file app.py.
    The files are both on my computer at the moment. The addresses of the files are
    C:\……..\TEST\templates\index.html
    C:\……..\TEST\app.py
    There are no additional files in the folder structure under TEST.

    For debugging purposes I added a text line to the html page which is empty on load and is filled with the text “You did click the button.” by the function “myfunction_clickevent()” when clicking the button. It works fine. So the html+javascript code seem to work properly.
    I also tried with giving the full address of the script.
    I also tried with a different python script which starts an R script (This is actually what I am planning to do, to play with some data from a database) but also nothing happens.

    Did I do any obvious mistakes? Or how can I further debug this problem?
    How does the javascript logic know where to look for the “app.py”, especially when doing the click event where in the function the “app.py” isn’t explicitly named (what if there were more than one python script in the same folder)?

    Kind regards
    Barbara

    Reply
    1. admin says:
      January 2, 2023 at 4:21 pm

      Hi Barbara,

      Can I ask how you are runniing this code. What I mean is are you running through Python Idle?

      My initial thoughts are the templates location should be within the application folder not a local folder.

      Have you tried debugging, or running it an application such as Pycharm , that is where I did my coding.

      Please let us know, so can look at further.

      Thanks,

      Data Analytics Ireland

      Reply
      1. Barbara says:
        January 6, 2023 at 9:11 pm

        Hi Data Analytics,

        thank you for replying. I am coding in VS Code.
        We found the error I made, it was quite simple and stupid, and due to a complete lack of understanding on my side with regards to how things are supposed to function.

        I did not run the python code to start the web server before opening the web page. I just assumed it is supposed to sit there, waiting for the Javascript to start it, like my R script which is started by the Python script. So I just ran it once to make sure it doesn’t show any errors and then stopped it. I then opened the web page via the index.html, not through the IP address http://127.0.0.1:5000/

        Your explanation and video doesn’t say explicitly (or I overlooked it) in which order to run things and the title is “How to run Python directly from Javascript”. Hence my conclusion. I guess it is a little like learning to drive a car (or using any type of machine) without knowing that it has to be started before the thing takes any commands. I believe while looking through the comments under your youtube video I saw that there was at least 1 person who maybe had the same problem I was having.

        Anyway, it now works as intended.
        Kind regards
        Barbara

        Reply
        1. admin says:
          January 14, 2023 at 9:05 pm

          Hi Barbara,

          That is great you got it resolved. It does take a while to understand parts of this, but once you get to understand more, the troubleshooting becomes easier.

          Regards,

          Data Analytics Ireland

          Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Select your language!

  • हिंदी
  • Español
  • Português
  • Français
  • Italiano
  • how do I merge two dictionaries in Python? Python
  • ValueError: invalid literal for int() with base 10 Value Error
  • How to Generate Random Integers Between 0 and 9 Python
  • How to create a class in Python class
  • YouTube channel lists – Python DataFrames Python Dataframe
  • python constructor self and __init__explained Python
  • How to check if a file is empty Python
  • how to use case statements in SQL SQL

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT