简体   繁体   中英

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

By using flask, You need to write Ajax call in .js .

Sample Ajax call.

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

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

Flask and Django are two examples of Python based web frameworks which use Jinja . They will both allow for calling a backend script, and passing the results into variables held within the web page code.

With 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. Here is the link: http://skulpt.org/using.html

I am not sure if it fits into your needs, but have a look at this:
PyPy.Js

It is an Python interpreter written in JavaScript. 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.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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