繁体   English   中英

如何通过 HTML 按钮运行 Python 脚本?

[英]How to run Python script through HTML button?

我想通过 HTML 按钮运行 Python 脚本。 我没有使用任何服务器。

我尝试使用本地服务器,但它给出了这个错误: jquery-3.3.1.min.js:2 GET http://127.0.0.1:8080/home/techm/Documents/labelImg-master/labelImg.py 404 (Not Found)

而且我尝试不使用服务器也出现此错误: jquery-3.3.1.min.js:2 Failed to load file:///home/techm/Documents/labelImg-master/labelImg.py: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

这是我的 HTML 代码:

<!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: "/home/techm/Documents/labelImg-master/run.sh",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

有没有其他方法可以单击 HTML 页面中的按钮并自动运行 python 脚本。

不幸的是,您尝试做的事情是不可能的。 要运行位于文件系统上的 Python 脚本,您必须在终端中运行它,而通过导航器无法做到这一点。

我建议您设置一个快速服务器来为您执行此操作。

node.js 服务器:

const http = require('http');
const { exec } = require('child_process');
const fs = require('fs');

//create a server object:
http.createServer(function (req, res) {

  //if the request url is: localhost:8080
  if(req.url === "/"){
    fs.readFile("index.html", function(err, data){
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(data);
      res.end();
    });
  //if the request url is: localhost:8080/run
  }else if(req.url === "/run"){


    exec('./ /home/techm/Documents/labelImg-master/run.sh', (error, stdout, stderr) => {
     if (error) {
       console.error(`exec error: ${error}`);
       res.write('Command has failed'); //write a response to the client
       res.end(); //end the response
       return;
     }
     console.log(`stdout: ${stdout}`);
     console.log(`stderr: ${stderr}`);

     res.write('Command has been run'); //write a response to the client
     res.end(); //end the response
    });
  }

}).listen(8080); //the server object listens on port 8080

将上述内容放入名为(例如) server.js的文件中后,通过在终端中键入node server.js来运行服务器(与该文件位于同一目录中)

那么你的ajax应该是这样的。

$.ajax({
  url: "/run",
  context: document.body
}).done(function(data) {
  //data should contain what the server responds, in this case "Command has been run"
  console.log(data);
});

使用 Brython 怎么样? 这是一个用于客户端的python解释器。

这是网站。

https://brython.info/index.html

你可以像这样使用它,

<div id="editor">
    print(123)
</div>
<button id="btn">Run Python</button>

...

<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/stable/www/src/brython.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/stable/www/src/brython_stdlib.js"></script>
<script type="text/python">
    from browser import doc, window
    from browser import html

    def exec_python():
        exec(doc['editor'].value)

    doc['btn'].bind('click', exec_python)
</script>

由于安全原因,您无法通过 javascript 函数访问您的文件系统。

您唯一能做的就是禁用浏览器的安全性。

如果您使用 Chrome,请像这样启动您的 chrome:

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/tempFolderForChromeThings

我发现了一种从浏览器按钮启动 python 脚本的非常简单的方法,但在浏览器之外运行。 您不必安装任何其他软件。 没有服务器,没有网络权限,没有新的协议注册,什么都不需要。

  1. 编译您的 python 脚本以获取 .pyc 文件。 在 python 外壳上:
 import py_compile py_compile.compile ('myscript.py')
  1. 在html中定义一个按钮:
 <button type="button" onclick="runOnPython()">RunOnPython</button>
  1. 定义一个简单的 javascript 函数,当按钮被点击时执行:
 function runOnPython() { window.open("myScript.pyc") }

确保路径信息完整。 这里为了简单起见,假设 html 和 python 脚本位于同一目录中。 如果不同,请提供 myScript.pyc 文件的完整路径信息。

当您单击该按钮时,会弹出著名的打开文件方式/保存文件对话框。 默认 python exe 被列为打开应用程序。 所以,再点击一次。 就是这样。 您的 Python 脚本开始执行。

不幸的是,消除第二次按钮点击不是很容易; 因为“始终对此类文件执行相同操作”选项已禁用。 您在选项 -> 文件下载首选项中所做的设置也没有任何区别。 您必须在浏览器的配置文件文件夹中编辑 MimeTypes.rdf 文件; 我没有尝试。

以上场景在 Python 3.6.5 和 Firefox 65.0 上测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM