如何从html按钮执行python脚本? [英] How can I execute a python script from an html button?

查看:720
本文介绍了如何从html按钮执行python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,我已经在计算机上保存了许多python脚本,我创建了一个只有一个按钮的html文件.而是进入终端并运行python <path to script>,我想这样做,以便在单击该按钮时启动我的python脚本之一.这可能/如何做到?

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?

出于示例目的,我们将脚本称为MYSCRIPT.py.我做了一些研究,但没有提出任何希望.我知道以下代码是不正确的,但仅出于起点考虑,这是我的html文件.

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.

<!DOCTYPE html>
<html>
    <body>
        <head>

           <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="exec('python MYSCRIPT.py');">

        </head>
    </body>
</html>

推荐答案

由于您要求在HTML页面中完成此操作的方法,因此我正在回答此问题.我觉得没有必要提及严重的警告和暗示..我相信您知道.py脚本的安全性比我更好:-)

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 :-)

我会在jQuery库中使用.ajax()函数.只要脚本位于公共可访问的html目录中,这将允许您调用Python脚本 ...也就是说,这是我告诉您要注意安全预防措施的部分...

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 ...

<!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>

此外..值得注意的是,您的脚本将必须具有例如www-data用户的适当权限才能运行它... A chmod和/或可能是必需的.

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.

这篇关于如何从html按钮执行python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆