You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask网页按钮执行Python脚本遇404错误求助(封闭网络环境)

解决Flask网页按钮执行脚本的404错误问题

问题原因

你现在的写法是让前端直接请求USB.py文件,但Flask不会自动识别并执行这种文件请求,必须通过Flask专门定义的路由接口来触发脚本执行,所以才会出现404错误。

简单易懂的解决方案

1. 修改Flask主文件(比如你的主文件是app.py)

在原代码基础上,添加执行脚本的路由,同时导入执行外部脚本需要的subprocess模块:

from flask import Flask, render_template
import subprocess  # 用来执行外部Python脚本
app = Flask(__name__)

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

# 新增:专门处理执行USB.py的路由
@app.route('/run-usb')
def run_usb_script():
    # 用python命令运行USB.py,替换成你实际的脚本绝对路径
    subprocess.run(["python3", "/home/joe/USB.py"])
    return "脚本执行完成"  # 返回给前端的提示内容

if __name__ == '__main__':
        app.run(debug=True, port=80, host='0.0.0.0')

2. 修改HTML文件(index.html)

把AJAX请求的url改成上面新增的路由/run-usb:

<!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: "/run-usb",  // 这里改成新增的路由
             context: document.body
            }).done(function() {
             alert('finished python script');
            });
        }
    </script>
  </body>
</html>

3. 权限检查(可选)

如果执行时提示权限问题,在树莓派终端执行命令给脚本加权限:

chmod +x /home/joe/USB.py

4. 扩展到USB2.py

如果要执行USB2.py,只需再新增一个路由:

@app.route('/run-usb2')
def run_usb2_script():
    subprocess.run(["python3", "/home/joe/USB2.py"])
    return "USB2脚本执行完成"

然后在HTML里加一个对应按钮,把goPython函数里的请求地址改成/run-usb2即可。

内容的提问来源于stack exchange,提问作者Ian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 17:13:32