简体   繁体   中英

How to execute python script from a button in HTML page

I've to run a python script from my HTML page button. When I click on the button, it should run the command "python filename.py". But I'm not getting any solutions, please help!

Thank You

Sorry to say but this is not possible unless your 'filename.py' is on a server eg flask, or else this will not work. If setup a flask server, and with a certain route it runs your code, then you can have your HTML code make a POST or GET request to this flask server, and the code should run.

Attach a listener to the button and have that listener call your endpoint:

document.querySelector('button')
  .addEventListener(() => fetch('runMyScript.php', { method: 'POST' }));

Then have that endpoint run your desired program. In PHP, for example:

<?php
// if you want the page to be able to do something with the result:
$output = `python /home/username/filename.py 2>&1`;
echo $output;
?>

Of course, a real setup better have something to validate

You can't.

Python runs in the server. HTML isn't a programming language, it's content, and it sits in the browser. About the best you can do is use AJAX to call a function in the server (which you'd have written in Python) and, if it returns a value, return it via AJAX.

You have to use Php to make a command line call to run your python script. There is an "exec" function in php which is used for executing command line operations.

So, you have to write the following command in your button click operation:

exec('python filename.py');

In the above command, provide the complete path to your python script.

A sample php code which is integrable with html tags and can execute python script is given below:

<html><body>
<input type="button" name="runmyscript" value=" Run Python code " onClick=" 
<? exec('python filename.py'); ?>">
</body></html>

You can use this link for your reference: https://www.raspberrypi.org/forums/viewtopic.php?t=24930

However, please make sure that python is in your system variable "path" and you are able to execute "python filename.py" command directly from your command prompt.

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