Lokesh Singh
Lokesh Singh

Reputation: 75

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

Upvotes: 0

Views: 6523

Answers (3)

PHP Geek
PHP Geek

Reputation: 4033

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.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370619

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

Upvotes: 0

Ben10
Ben10

Reputation: 498

Sorry to say but this is not possible unless your 'filename.py' is on a server e.g. 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.

Upvotes: 2

Related Questions