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