【问题标题】:How to run .exe file on HTML button click?如何在 HTML 按钮单击时运行 .exe 文件?
【发布时间】:2021-06-14 06:10:26
【问题描述】:

我目前正在使用烧瓶建立一个网站。我的烧瓶页面使用可下载的可执行文件包。我想知道如何编写一个 html 按钮,以便在单击按钮时运行本地 exe 文件。

假设我有一个名为 test.exe 的文件。这就是我的想象: 网站.py

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

@app.route(“/home”)
def home():
    return render_template(“button.html”)

button.html

<button onclick=open/run test.exe>
</button>

我会用什么代码代替“打开/运行 test.exe”?

【问题讨论】:

  • 如果您的意思是在下载后不可行。浏览器无法访问在窗口上下文中下载的实际文件会发生什么,甚至无法访问任何下载进度
  • 我认为你可以让一个 HTML 按钮从你的系统中执行一个可执行文件。这甚至可能吗?
  • 不直接,不。想一想,如果某个随机站点在您的设备上执行任何操作,将会带来多大的安全风险。您在浏览器窗口中运行的代码位于一个非常孤立的沙箱中

标签: python html executable


【解决方案1】:

这只有在服务器托管在计算机上时才有效,否则它可能非常不安全。否则你不能这样做。

Python:

@app.route("/") # page with button
def myPage():
  return "<button onclick=\"var xhttp=new XMLHttpRequest;xhttp.open('GET','/openexe',!0),xhttp.send();\">run my file</button>"

@app.route("/openexe")
def openEXE():
  os.system("path/to.exe")
  return "done"

这会打开一个返回给服务器的请求,当服务器收到这个请求时,可执行文件就会打开。

【讨论】:

  • 您在 Python 上使用了哪个库?这个看起来很可爱的图书馆。
  • @HasanDelibaş 这是 Flask,正如作者所说他们正在使用 Flask。
【解决方案2】:

您必须编写本地服务。但要注意安全。

  • 网站 (HTML)
  • 本地应用运行程序(exe文件:在8001上监听)

算法

**HTML 调用示例**

<button>Run Program</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
$("button").click(function(){
  $.get("//localhost:8001", function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});
</script>

应用运行程序示例

# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import subprocess

hostName = "localhost"
serverPort = 8001

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        # IMPORTANT ENABLE HERE CORS 
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<ok>Run Start Program</ok>", "utf-8"))
        # CHANGE HERE
        subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])


if __name__ == "__main__":        
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")

【讨论】:

  • 作者指定他们使用的是烧瓶,所以你的例子不是他想要的。
  • 先不说flask库。在他-她编辑之后。你可以看到:*.com/revisions/67780851/1
最近更新 更多