如何从 html 按钮执行 python 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48552343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I execute a python script from an html button?
提问by Justin Smith
I have a number of python scripts that I have saved on my computer, out of curiosity I have created an 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?
我在计算机上保存了许多 python 脚本,出于好奇,我创建了一个只有一个按钮的 html 文件。而不是进入终端并运行python <path to script>
,我想让它在单击该按钮时启动我的一个 python 脚本。这可能/如何做到?
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.
出于示例目的,我们将调用要运行的脚本 MYSCRIPT.py。我做了一些研究,但没有提出任何有希望的。我知道以下代码是不正确的,但这里是我的 html 文件的起点。
<!DOCTYPE html>
<html>
<body>
<head>
<input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="exec('python MYSCRIPT.py');">
</head>
</body>
</html>
回答by Zak
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 :-)
由于您要求一种在HTML
页面内完成此操作的方法,因此我正在回答此问题。我觉得没有必要提及随之而来的严重警告和影响..我相信你.py
比我更了解你的脚本的安全性:-)
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 ...
我会使用库.ajax()
中的jQuery
函数。只要脚本位于可公开访问的 html 目录中,这将允许您调用Python
脚本 ......也就是说,这是我告诉您注意安全预防措施的部分......
<!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.
此外.. 值得注意的是,您的脚本必须具有适当的权限,例如,www-data
用户才能运行它...... Achmod
和/或 achown
可能是必要的。
回答by Phok Chanrithisak
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 Flaskpip 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
1.首先你需要在你的命令提示符中安装Flaskpip install flask
,它是一个 python 微框架,不要害怕你需要有另一个先验知识来学习,它真的很简单,只有几行代码。
如果你希望你为新手快速学习 Flask,这里是我也从Flask 初学者教程 (YouTube) 中学习的教程
2. 创建一个新文件夹
- 第一个文件将是
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 templatesfile will be your html file
index.html
-2nd 在上一个文件夹中创建另一个子文件夹并将其命名为模板文件将是您的 html 文件
index.html
<!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 folderdirectory, 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.
3.. 要运行,打开命令提示符到新文件夹目录,键入python server.py
运行脚本,然后转到浏览器类型localhost:5000
,然后您将看到按钮。您可以单击并路由到您创建的目标脚本文件。
Hope this helpful. thank you.
希望这有帮助。谢谢你。
回答by kavin
Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Djangobecause it's more powerful. Here is Step by guide to get complete your task :
最好的方法是使用 Python Web Frame Work,您可以选择Django/Flask。我建议你使用Django,因为它更强大。以下是完成任务的分步指南:
pip install django
django-admin createproject buttonpython
then you have to create a file name views.py in buttonpython directory.
那么你必须在 buttonpython 目录中创建一个文件名 views.py 。
write below code in views.py:
在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
完成后导航到 urls.py 并添加此节
from . import views
path('', include('blog.urls')),
Now go to parent directory and execute manage.py
现在转到父目录并执行 manage.py
python manage.py runserver 127.0.0.1:8001
Step by Step Guide in Detail: Run Python script on clicking HTML button
详细分步指南:单击 HTML 按钮运行 Python 脚本
回答by Michael Dennis
This would require knowledge of a backend website language.
这需要了解后端网站语言。
Fortunately, Python's Flask Libraryis a suitable backend language for the project at hand.
幸运的是,Python 的Flask 库是适合手头项目的后端语言。
Check out this answerfrom another thread.
从另一个线程查看此答案。
回答by user13247146
you could use text files to trasfer the data using PHP and reading the text file in python
您可以使用文本文件使用 PHP 传输数据并在 python 中读取文本文件
回答by Mieszko
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 方案,即。您需要在您的机器上注册和配置它,然后将具有该方案的 url 挂接到按钮上。
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.
URI 方案是 URI 之前的部分://
。例如,标准 URI 方案是https
orftp
或file
。但是有像fx这样的自定义。mongodb
. 你需要的是你自己的,例如mypythonscript
。它可以配置为 exec 脚本,甚至只是在 params 中带有脚本名称的 python。这当然是灵活性和安全性之间的权衡。
You can find more details in the links:
您可以在以下链接中找到更多详细信息:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
EDIT:Added more details about what an custom scheme is.
编辑:添加了有关自定义方案是什么的更多详细信息。
回答by BareNakedCoder
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 ...
我已经在 Windows 上做到了这一点。我有一个本地 .html 页面,用作我当前所有工作的“仪表板”。除了通常的链接之外,我还能够添加可点击的链接来打开 MS-Word 文档、Excel 电子表格、打开我的 IDE、ssh 到服务器等。这有点复杂,但我是这样做的……
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
)
首先,更新 Windows 注册表。您的浏览器处理常见的协议,如 http、https、ftp。您可以定义自己的协议和在单击该协议类型的链接时要调用的处理程序。这是配置(运行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.
有了这个,当我有一个像 的链接时<a href="mydb:open:ProjectX.docx">ProjectX</a>
,单击它会调用C:\_opt\Dashboard\Dashboard.vbs
传递给它的命令行参数open:ProjectX.docx
。我的 VBS 代码查看此参数并执行必要的操作(在这种情况下,因为它以 .docx 结尾,因此它会调用 MS-WordProjectX.docx
作为它的参数。
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).
现在,我在 VBS 中编写处理程序只是因为它是非常旧的代码(例如 15 年以上)。我还没有尝试过,但是您也许可以编写一个 Python 处理程序 , Dashboard.py
。我会让你来写你自己的处理程序。对于您的脚本,您的链接可能是href="mydb:runpy:whatever.py"
(runpy:
前缀告诉您的句柄使用 Python 运行)。
回答by Jason Sperske
Using a UI Framework would be a lot cleaner (and involve fewer components). Here is an example using wxPython:
使用 UI 框架会更简洁(并且涉及更少的组件)。下面是一个使用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!
我还没有测试过这个,我相信有从 python 脚本启动 python 脚本的更简洁的方法,但我认为这个想法仍然成立。祝你好运!