html按钮调用python_从HTML按钮运行Python脚本
时间: 2023-12-03 08:42:30 浏览: 303
要从 HTML 按钮调用 Python 脚本,可以通过 Ajax 请求将数据传递给后台 Python 脚本进行处理。以下是一个简单的示例:
1. 创建一个 HTML 页面,并在页面中添加一个按钮:
```html
<!DOCTYPE html>
<html>
<head>
<title>HTML Button to Run Python Script</title>
</head>
<body>
<button id="run-script-btn">Run Python Script</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
$("#run-script-btn").click(function() {
$.ajax({
url: "run_script.py",
type: "post",
data: {param1: "value1", param2: "value2"},
success: function(response) {
console.log(response);
},
error: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
</script>
</body>
</html>
```
2. 创建一个名为 `run_script.py` 的 Python 脚本,并在其中处理 Ajax 请求:
```python
import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html")
print()
form = cgi.FieldStorage()
param1 = form.getvalue("param1")
param2 = form.getvalue("param2")
# 在此处添加 Python 代码来处理参数并执行相应的操作
print("Script executed successfully!")
```
请注意,对于此示例,您需要在 Web 服务器上配置好 CGI 才能运行。如果您正在本地运行,则可以使用 Python 的内置 Web 服务器来运行此示例:
1. 在命令行中进入到您的 HTML 文件所在的目录。
2. 运行以下命令来启动 Python 内置 Web 服务器:
```
python -m http.server --cgi 8000
```
3. 在浏览器中访问 `http://localhost:8000`,单击 "Run Python Script" 按钮即可。
阅读全文
相关推荐


















