Python Web Tutorial #1

Click the button below to run a simple Python script.

My Page





Script 1. python-web-tutorial-2.py

Create a basic Python script that prints Hello World.  Name the script python-web-tutorial-1.py.

				
					print("Coder Fairy: Hello World!")
				
			

Script 2. python-web-tutorial-1.php

Create a php script that runs the Python script, stores the output of Python’s print statement, and then prints the results to the webpage.  Name this script python-web-tutorial-1.php.  python-web-tutorial-1.py in the script below should match the name of your Python script from the previous step.

				
					<?php
$output = shell_exec("python python-web-tutorial-2.py");
echo $output;
?>
				
			

Upload the Python and PHP scripts to your WordPress server:

1. Log into cPanel

2. Click on File Manager

3. Navigate to the folder that you would like to save these scripts to

4. Click Upload and then upload the two scripts python-web-tutorial-2.py and python-web-tutorial-2.php

Script 3. python-web-tutorial-2.html

Create a html and Javascript script.  The html portion creates a button with the id of “myButton“.  The Javascript portion that calls the php script from step 2 to gets the print statement from the Python script and then prints the output.

In the code below, replace https://coderfairy.com/code/python-web/2/python-web-tutorial-2.php with the location that you saved your php script in the previous step.

				
					<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My Page</title>
  </head>
  <body>
    <center><button id="myButton">Click me</button>
    <br><br>
    <font size = "14"><div id="output"></div></font></center>
    <br>
    <script>
      document.getElementById("myButton").addEventListener("click", function() { // add an event listener to the button
      document.getElementById("myButton").disabled = true; // disable the button to prevent multiple clicks
      document.getElementById("output").innerHTML = "Loading..."; // show a loading message
      fetch('https://coderfairy.com/code/python-web/2/python-web-tutorial-2.php') // fetch the data from the Python script
        .then(response => response.text())  // extract the response data as text
        .then(data => {
          document.getElementById("output").innerHTML = data; // update the HTML content of the page with the response data
          document.getElementById("myButton").disabled = false; // enable the button
        })
        .catch(error => {
          document.getElementById("output").innerHTML = "An error occurred."; // display an error message
          document.getElementById("myButton").disabled = false; // enable the button
        });
      });
    </script>
  </body>  
</html>

				
			
Scroll to Top