How to – “Display output of Python Code in your Browser” ?

How to – “Display output of Python Code in your Browser” ?

Introduction 

How to produce Python code output on the browser – and more importantly – why do we need it?

Many backend Python developers are focused only on getting their code working functionally and aren’t always bothered about how to deploy it – or how the end user is going to use it. If you need to make an application front-end to your Python code, you will need – 

  1. A front-end such as a browser or a GUI
  2. A back-end containing Python installation where Python code will run

In this blog, we use Flask to create a single-page web application which runs Python code on button click and also displays the output on the same screen.  

 

Intro To Flask

Flask and Django are the two Python based frameworks. Flask is suitable for creating smaller applications due to its limitations in certain areas – which we won’t discuss here. 

Despite its shortcomings for a full-fledged web application, Flask is very powerful for writing single-page web applications and APIs as it is written in Python and is suitable to run backend Python code. Its built-in development server and template engine enable rapid prototyping and easy rendering of dynamic HTML pages. Flask follows the WSGI standard, ensuring compatibility with various web servers. Its active community and extensive ecosystem of extensions provide additional functionalities, such as database integration and form handling.

Guidance to run HTML Code in Flask Step by Step

Step 1: Make sure Flask is installed. 

Type ‘pip install Flask ‘ in the command line at the Python prompt. 

 

Create a Python file, Example- runbtn.py to import Flask modules as shown.

How to – “Display output of Python Code in your Browser” ?
from flask import Flask, render_template, request

app = Flask(__name__)

Step 2: Next, create a Flask route and render a template: In your Flask route, you’ll render an HTML template that contains the file containing the HTML code that you want to display in the browser.

How to – “Display output of Python Code in your Browser” ?
@app.route('/')
def index():
    return render_template('buttonhtml3.html')

Step 3: Create an HTML template Example-  buttonhtml3.html.  

Note:  Always save HTML code inside the templates folder 

How to – “Display output of Python Code in your Browser” ?
<!DOCTYPE html>
<html>
<head>
    <title>Run Three Scripts</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<link rel="stylesheet" href="{{ url_for('static', filename='css/main2.css') }}">
</head>
<body>
<div class="head-div"><h2>Dashboard</h2></div>
<div class="script-div">
	<div class="fst-div">
	<div class="btn-div">
		<button id="script1">Run Script1</button> 
		<script>
			$(document).ready(function() {
			 $("#script1").click(function() {
			  $.ajax({
			   url: '/run_script',
			   type: 'POST',
			   success: function(response) {
				$("#output-div").html(response);
			   },
			   error: function(error) {
				console.log(error);
			   }
			    });
			  });
			});
		</script>
	</div>
	<hr>
	<div class="output-div">
	<p>Output:</p>
	</div>
	<div id="output-div" class="output-div"></div>
	</div>
</div>
</body>
</html>

Step 4:  Inside the command prompt, navigate to your project folder and run the Flask application using your <file name.py>  Example-  runbtn.py

 

How to – “Display output of Python Code in your Browser” ?
runbtn.py
Python code output

After running the command message as shown in the screenshot, open the browser (Chrome, Edge, etc.) and enter the URL:  http://127.0.0.1:5000/   to see the output of your application

 

How To Add Script in Flask?

Step 1: Create a separate Python script with your code Example- we are using hello3.py file

How to – “Display output of Python Code in your Browser” ?
# hello_script.py

import numpy
import pandas

print("start executing python script"+"
")
print("Hello, World!"+"
")
print("This is a Python script."+"
")
print("Flask is awesome!"+"
")
print("done executing python script"+"
")
 

Step 2:  Import subprocess module in flask application runbtn.py file. It help to run script when user click on the button

How to – “Display output of Python Code in your Browser” ?
from flask import Flask, render_template, request
import subprocess

app = Flask(__name__) 

How we  can render the script in Flask application file check code below 

How to – “Display output of Python Code in your Browser” ?
@app.route('/run_script', methods=['POST'])
def run_script():
    try:
        output = subprocess.check_output(['python', 'hello3.py'], text=True)
        return output
    except subprocess.CalledProcessError:
        return "Error executing Script 1"

In the HTML file, the button uses a separate AJAX request to the respective Flask route that runs the corresponding script – as shown in the code snippet below. 

How to – “Display output of Python Code in your Browser” ?
<div class="fst-div">
<div class="btn-div">
<button id="script1">Run Script1</button> 
<script>
	$(document).ready(function() {
			$("#script1").click(function() {
			$.ajax({
			url: '/run_script',
			type: 'POST',
			success: function(response) {
			$("#output-div").html(response);
			},
			error: function(error) {
			console.log(error);
			}
			});
		});
	});
</script>
</div>
<hr>
<div class="output-div">
<p>Output:</p>
</div>
<div id="output-div" class="output-div"></div>
</div>

After writing the HTML, save the files and run flask application by refreshing your browser to see the output.

How to add a CSS File in Flask?

The CSS file gets added in the standard way inside the HTML header. For Example- 

<link rel=”stylesheet” href=”{{ url_for(‘static’, filename=’css/main2.css’) }}”>

Note: The CSS file is placed under the following directory structure –  static-> css -> main.css, where main.css is your css file associated with buttonhtml3.html file.
 

How to – “Display output of Python Code in your Browser” ?
<head>
    <title>Run Three Scripts</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<link rel="stylesheet" href="{{ url_for('static', filename='css/main2.css') }}">
</head>

Conclusion

Using Flask, it is easy to run your Python scripts on button press and display the output within the browser.  It is a useful application when the user needs only a front-end environment to run Python code or when the user does not know how to execute a Python script.