43

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 MYSCRIPT.py. 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>
<html>
    <body>
        <head>

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

        </head>
    </body>
</html>
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
Justin Smith
  • 501
  • 2
  • 6
  • 8
  • 12
    Webpages are not allowed to run shell commands, as that would e very dangerous. Image going to a site that can run any command in your shell. What you would need is a server, that you send a request to and the server runs the command there. – mdatsev Jan 31 '18 at 22:17
  • Possible duplicate of [Running Python scripts from HTML button](https://stackoverflow.com/questions/47894506/running-python-scripts-from-html-button) – Obsidian Age Jan 31 '18 at 22:17
  • You'll need to use AJAX to call the script. –  Jan 31 '18 at 22:17
  • Just found [this](https://stackoverflow.com/questions/15166941/create-html-button-to-run-python-script) on another post, maybe it will help. – JakeTheSnake Jan 31 '18 at 22:18
  • 4
    Body is after Head, not inside – azro Jan 31 '18 at 22:18
  • I would run a jQuery AJAX call to the script itself .. This script will have to reside in the public `html` directory and accessible by a browser. http://api.jquery.com/jquery.ajax/ – Zak Jan 31 '18 at 22:18
  • Doing this in HTML (and therefor in a browser) would be much more complicated than a basic UI built with something like WXPython https://www.wxpython.org/pages/overview/#hello-world – Jason Sperske Jan 31 '18 at 22:18
  • Windows, Linux, or Mac? – BareNakedCoder Jan 31 '18 at 22:19
  • Wait, are you asking for an approach to run Python scripts locally or on a server remotely? – Jason Sperske Jan 31 '18 at 22:19
  • @JasonSperske locally for now – Justin Smith Jan 31 '18 at 22:21
  • Then a UI framework like wxPytyon would be a lot cleaner, I'll work on a simple example of this...one sec – Jason Sperske Jan 31 '18 at 22:22
  • What do you ultimately want to accomplish with this? Because [this](https://stackoverflow.com/a/47949174/3491991) can do exactly what you want, just like a number of other frameworks (like the mentioned wxPython, Flask or Django). But each implementation varies in difficulty and aim... – zelusp Jan 31 '18 at 22:30

7 Answers7

29

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 or pip3 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 server.py

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

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/my-link/')
def my_link():
  print ('I got clicked!')

  return 'Click.'

if __name__ == '__main__':
  app.run(debug=True)
  • 2nd create another subfolder inside previous folder and name it as templates and create index.html file inside it

<!doctype html>


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

    </body>

3. To run, open command prompt to the New Folder you created earlier, type python server.py or python3 server.py to run the script, then you will get response in your terminal/command prompt that server is running on http://127.0.0.1:5000 or any other ports. After that you go to browser type localhost:5000 or http://127.0.0.1:5000, then you will see button. You can click and route to destination script file you created.

Hope this helpful. thank you.

Chanrithisak Phok
  • 1,590
  • 1
  • 19
  • 29
13

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>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
        function goPython(){
            $.ajax({
              url: "MYSCRIPT.py",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

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.

Zak
  • 6,976
  • 2
  • 26
  • 48
  • this would mainly be dangerous if this is a script with a web server correct like flask or django? If this was just an simple html file and python file in the same directory running a script on a local machine... this would not be dangerous or am I missing something – Mike Sandstrom Feb 26 '20 at 05:52
  • The only security risk is that which is present for all server-side files. If someone can access the file *directly* and manipulate inputs / injections to get a result that may display sensitive information like the server directory structure or tables within the database. – Zak Feb 26 '20 at 16:03
  • 1
    -- It's the programming **within** the `.py` file that can be the security risk if not properly locked down. Usually if it's already part of a framework, most of those security concerns are already addressed within the framework. – Zak Feb 26 '20 at 16:08
  • understood. so assuming the only parts involved in the project are a simple html file with a button and a python script that runs onclick from within a local machine...the biggest security concern is someone unauthorized getting access to that file. – Mike Sandstrom Feb 26 '20 at 21:13
  • This does not work. I recieve a 405 error reponse. I think I need a backend solution in order to work, because calling a .py file from the frontend it doesnt work. – Sebastian Paduano Feb 28 '21 at 12:02
3

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 views.py in buttonpython directory.

write below code in views.py:

from django.http import HttpResponse

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

Once done navigate to urls.py and add this stanza

from . import views

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

Now go to parent directory and execute manage.py

python manage.py runserver 127.0.0.1:8001

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

kavin
  • 113
  • 2
  • 14
2

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.

1

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)

[HKEY_CLASSES_ROOT\mydb]
@="URL:MyDB Document"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\mydb\shell]
@="open"

[HKEY_CLASSES_ROOT\mydb\shell\open]

[HKEY_CLASSES_ROOT\mydb\shell\open\command]
@="wscript C:\_opt\Dashboard\Dashboard.vbs \"%1\""

With this, when I have a link like <a href="mydb:open:ProjectX.docx">ProjectX</a>, clicking it will invoke C:\_opt\Dashboard\Dashboard.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, Dashboard.py, instead. I'll leave it up to you to write your own handler. For your scripts, your link could be href="mydb:runpy:whatever.py" (the runpy: prefix tells your handle to run with Python).

BareNakedCoder
  • 3,257
  • 2
  • 13
  • 16
0

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:

https://support.shotgunsoftware.com/hc/en-us/articles/219031308-Launching-applications-using-custom-browser-protocols

https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx

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

Mieszko
  • 330
  • 2
  • 6
0

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

Zax71
  • 45
  • 7