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>
This question is related to
javascript
python
html
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
server.py
from flask import Flask, render_template_x000D_
app = Flask(__name__)_x000D_
_x000D_
@app.route('/')_x000D_
def index():_x000D_
return render_template('index.html')_x000D_
_x000D_
@app.route('/my-link/')_x000D_
def my_link():_x000D_
print ('I got clicked!')_x000D_
_x000D_
return 'Click.'_x000D_
_x000D_
if __name__ == '__main__':_x000D_
app.run(debug=True)
_x000D_
-2nd create another subfolder inside previous folder and name it as templates file will be your html file
index.html
<!doctype html>_x000D_
_x000D_
_x000D_
<head><title>Test</title> _x000D_
<meta charset=utf-8> </head>_x000D_
<body>_x000D_
<h1>My Website</h1>_x000D_
<form action="/my-link/">_x000D_
<input type="submit" value="Click me" />_x000D_
</form>_x000D_
_x000D_
<button> <a href="/my-link/">Click me</a></button>_x000D_
_x000D_
</body>
_x000D_
3.. To run, open command prompt to the New folder directory, type python server.py
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.
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.
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.
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
you could use text files to trasfer the data using PHP and reading the text file in python
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://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
EDIT: Added more details about what an custom scheme is.
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).
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)
panel.SetSizer(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()
frame.Show()
app.MainLoop()
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!
Source: Stackoverflow.com