[Solved] How can I execute a python script from an html button?

I have a number of python scripts that I have saved on my computer, out of curiosity I have created a html file that just has one button. Instead on going into the terminal and running python <path to script>, I would like to make it so when that button is clicked, is kicks off one of my python scripts. Is this possible/how can it be done?

for example purposes we’ll call the script to be run I’ve done a little research but have come up with nothing promising. I’m aware the following code is incorrect but just for a starting point here is my html file.

<!DOCTYPE html>

           <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="exec('python');">


Solution #1:

There are various ways to make it done, very simple technique with security peace in mind, here might help you

1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don’t be afraid that you need to have another prior knowledge to learn that, it’s really simple and just a few line of code.
If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)

2.Create a new folder
– 1st file will be

from flask import Flask, render_template
app = Flask(__name__)

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

def my_link():
  print ('I got clicked!')

  return 'Click.'

if __name__ == '__main__':

-2nd create another subfolder inside previous folder and name it as templates file will be your html file

<!doctype html>

    <meta charset=utf-8> </head>
        <h1>My Website</h1>
        <form action="/my-link/">
            <input type="submit" value="Click me" />
        <button> <a href="/my-link/">Click me</a></button>


3.. To run, open command prompt to the New folder directory, type python to run the script, then go to browser type localhost:5000, then you will see button. You can click and route to destination script file you created.

Hope this helpful. thank you.

Respondent: Phok Chanrithisak

Solution #2:

Since you asked for a way to complete this within an HTML page I am answering this. I feel there is no need to mention the severe warnings and implications that would go along with this .. I trust you know the security of your .py script better than I do 🙂

I would use the .ajax() function in the jQuery library. This will allow you to call your Python script as long as the script is in the publicly accessible html directory … That said this is the part where I tell you to heed security precautions …

<!DOCTYPE html>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

        function goPython(){
              url: "",
             context: document.body
            }).done(function() {
             alert('finished python script');;

In addition .. It’s worth noting that your script is going to have to have proper permissions for, say, the www-data user to be able to run it … A chmod, and/or a chown may be necessary.

Respondent: Zak

Solution #3:

This would require knowledge of a backend website language.

Fortunately, Python’s Flask Library is a suitable backend language for the project at hand.

Check out this answer from another thread.

Respondent: Michael Dennis

Solution #4:

Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Django because it’s more powerful.
Here is Step by guide to get complete your task :

pip install django
django-admin createproject buttonpython

then you have to create a file name in buttonpython directory.

write below code in

from django.http import HttpResponse

def sample(request):
    #your python script code
    output=code output
    return HttpResponse(output)

Once done navigate to and add this stanza

from . import views

path('', include('blog.urls')),

Now go to parent directory and execute

python runserver

Step by Step Guide in Detail: Run Python script on clicking HTML button

Respondent: kavin

Solution #5:

It is discouraged and problematic yet doable. What you need is a custom URI scheme ie. You need to register and configure it on your machine and then hook an url with that scheme to the button.

URI scheme is the part before :// in an URI. Standard URI schemes are for example https or ftp or file. But there are custom like fx. mongodb. What you need is your own e.g. mypythonscript. It can be configured to exec the script or even just python with the script name in the params etc. It is of course a tradeoff between flexibility and security.

You can find more details in the links:

EDIT: Added more details about what an custom scheme is.

Respondent: Mieszko

Solution #6:

I’ve done exactly this on Windows. I have a local .html page that I use as a “dashboard” for all my current work. In addition to the usual links, I’ve been able to add clickable links that open MS-Word documents, Excel spreadsheets, open my IDE, ssh to servers, etc. It is a little involved but here’s how I did it …

First, update the Windows registry. Your browser handles usual protocols like http, https, ftp. You can define your own protocol and a handler to be invoked when a link of that protocol-type is clicked. Here’s the config (run with regedit)

@="URL:MyDB Document"
"URL Protocol"=""



@="wscript C:_optDashboardDashboard.vbs ""%1"""

With this, when I have a link like <a href="">ProjectX</a>, clicking it will invoke C:_optDashboardDashboard.vbs passing it the command line parameter open:ProjectX.docx. My VBS code looks at this parameter and does the necessary thing (in this case, because it ends in .docx, it invokes MS-Word with ProjectX.docx as the parameter to it.

Now, I’ve written my handler in VBS only because it is very old code (like 15+ years). I haven’t tried it, but you might be able to write a Python handler,, instead. I’ll leave it up to you to write your own handler. For your scripts, your link could be href="" (the runpy: prefix tells your handle to run with Python).

Respondent: BareNakedCoder

Solution #7:

you could use text files to trasfer the data using PHP and reading the text file in python

Respondent: Zax71

Solution #8:

Using a UI Framework would be a lot cleaner (and involve fewer components). Here is an example using wxPython:

import wx
import os
class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Launch Scripts")
        panel = wx.Panel(self, wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        buttonA = wx.Button(panel, id=wx.ID_ANY, label="App A", name="MYSCRIPT")
        buttonB = wx.Button(panel, id=wx.ID_ANY, label="App B", name="MYOtherSCRIPT")
        buttonC = wx.Button(panel, id=wx.ID_ANY, label="App C", name="SomeDifferentScript")
        buttons = [buttonA, buttonB, buttonC]

        for button in buttons:
            self.buildButtons(button, sizer)


    def buildButtons(self, btn, sizer):
        btn.Bind(wx.EVT_BUTTON, self.onButton)
        sizer.Add(btn, 0, wx.ALL, 5)

    def onButton(self, event):
        This method is fired when its corresponding button is pressed, taking the script from it's name
        button = event.GetEventObject()

        os.system('python {}.py'.format(button.GetName()))

        button_id = event.GetId()
        button_by_id = self.FindWindowById(button_id)
        print "The button you pressed was labeled: " + button_by_id.GetLabel()
        print "The button's name is " + button_by_id.GetName()

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()

I haven’t tested this yet, and I’m sure there are cleaner ways of launching a python script form a python script, but the idea I think will still hold. Good luck!

Respondent: Jason Sperske

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy