简体   繁体   English

有没有办法从 web 浏览器执行 Python 脚本? [等候接听]

[英]Is there any way of executing a Python script from a web browser? [on hold]

I have a python script which I want to execute when someone clicks on a button in an HTML/PHP web page in the browser.我有一个 python 脚本,当有人在浏览器中单击 HTML/PHP web 页面中的按钮时,我想执行该脚本。 How can this be achieved and what is the best way of doing it?如何做到这一点,最好的方法是什么?

You need to use flask server for this requirement as browser can not access local file.您需要使用 flask 服务器来满足此要求,因为浏览器无法访问本地文件。

By using flask, You need to write Ajax call in .js .通过使用 flask,您需要在.js中编写 Ajax 调用。

Sample Ajax call.示例 Ajax 调用。

$(document).ready(function () {
  $('#<ButtonID>').click(function (event) {
    $.ajax({
      url: '/<Flask URL>',
      type: 'POST',
      success: function (data) {
        <DATA OBJECT>
      },
    });
    event.preventDefault();
  });
});

Sample Flask function样品 Flask function

@app.route('/<Flask URL>',methods=['POST'])
def result():
    try:
        <DO>
    except:
        logger.error()
        raise
    return jsonify({'data':<Python variable>})

You might need to import necessary modules.您可能需要导入必要的模块。

Look at exec https://www.php.net/manual/en/function.exec.php function if you're going to use pure PHP for this. Look at exec https://www.php.net/manual/en/function.exec.php function if you're going to use pure PHP for this.

Flask and Django are two examples of Python based web frameworks which use Jinja . FlaskDjango是基于 Z2567A5EC9705EB7AC2C984033E06 框架的Python的两个示例。 They will both allow for calling a backend script, and passing the results into variables held within the web page code.它们都允许调用后端脚本,并将结果传递到 web 页面代码中保存的变量中。

With exec ,使用exec

$command = "python script_path";
exec($command,$output,$return_var);
if ($return_var) {
    $error = error_get_last();
    var_dump($error)
}

You can use Skulpt library in your website to achieve your goal.您可以在您的网站中使用 Skulpt 库来实现您的目标。 Here is the link: http://skulpt.org/using.html这是链接: http://skulpt.org/using.html

I am not sure if it fits into your needs, but have a look at this:我不确定它是否符合您的需求,但请看一下:
PyPy.Js PyPy.Js

It is an Python interpreter written in JavaScript.它是用 JavaScript 编写的 Python 解释器。 Maybe you can do something with it.也许你可以用它做点什么。

Another option is to create an HTTP endpoint with for example Flask and let the button send a request to this endpoint which then executes the file.另一种选择是创建一个 HTTP 端点,例如 Flask 并让按钮向该端点发送请求,然后执行该文件。

Good luck!祝你好运!

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

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