How to run python script in webpage

Python

Python Problem Overview


I'm very new to Python. I just know what Python is. I have created the below code (In Python IDLE):

print "Hi Welcome to Python test page\n";
print "Now it will show a calculation";
print "30+2="; 
print 30+2;

Then I saved this page in my localhost as index.py

I run the script using http://localhost/index.py

But it does not show executed python script. Instead, it showed the above code as HTML. Where is the problem? please anyone tell me how to run a Python file in a webpage?

Python Solutions


Solution 1 - Python

In order for your code to show, you need several things:

Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.

Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.

Setting this up can be quite the hassle, so be prepared.

Solution 2 - Python

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

    #!/usr/bin/python
    print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

Solution 3 - Python

using flask library in Python you can achieve that. remember to store your HTML page to a folder named "templates" inside where you are running your python script.

so your folder would look like

  1. templates (folder which would contain your HTML file)
  2. your python script

this is a small example of your python script. This simply checks for plagiarism.

from flask import Flask
from flask import request
from flask import render_template
import stringComparison

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("my-form.html") # this should be the name of your html file

@app.route('/', methods=['POST'])
def my_form_post():
    text1 = request.form['text1']
    text2 = request.form['text2']
    plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
    if plagiarismPercent > 50 :
        return "<h1>Plagiarism Detected !</h1>"
    else :
        return "<h1>No Plagiarism Detected !</h1>"

if __name__ == '__main__':
    app.run()

This a small template of HTML file that is used

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Enter the texts to be compared</h1>
    <form action="." method="POST">
        <input type="text" name="text1">
        <input type="text" name="text2">
        <input type="submit" name="my-form" value="Check !">
    </form>
</body>
</html>

This is a small little way through which you can achieve a simple task of comparing two string and which can be easily changed to suit your requirements

Solution 4 - Python

If you are using your own computer, install a software called XAMPP (or WAMPP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to xampp folder and double click the htdocs folder. Now what you need to do is create an html file (I'm gonna call it runpython.html). (Remember to move the python file to htdocs as well)

Add in this to your html body (and inputs as necessary)

<form action = "file_name.py" method = "POST">
   <input type = "submit" value = "Run the Program!!!">
</form>

Now, in the python file, we are basically going to be printing out HTML code.

#We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.
    
    import cgitb
    import cgi
        
    cgitb.enable() #This will show any errors on your webpage
        
    inputs = cgi.FieldStorage() #REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']
        
    print "Content-type: text/html" #We are using HTML, so we need to tell the server
        
    print #Just do it because it is in the tutorial :P
        
    print "<title> MyPythonWebpage </title>"
        
    print "Whatever you would like to print goes here, preferably in between tags to make it look nice"

Solution 5 - Python

With your current requirement this would work :

    def start_html():
        return '<html>'

    def end_html():
        return '</html>'

    def print_html(text):
        text = str(text)
        text = text.replace('\n', '<br>')
        return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
        webpage_data =  start_html()
        webpage_data += print_html("Hi Welcome to Python test page\n")
        webpage_data += fd.write(print_html("Now it will show a calculation"))
        webpage_data += print_html("30+2=")
        webpage_data += print_html(30+2)
        webpage_data += end_html()
        with open('index.html', 'w') as fd: fd.write(webpage_data)

open the index.html and you will see what you want

Solution 6 - Python

Well, OP didn't say server or client side, so i will just leave this here in case someone like me is looking for client side:

http://skulpt.org/using.html

Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just a simple JS.

Solution 7 - Python

Python code/script can be run in the browser.

PyScript is a framework that allows users to create rich Python applications in the browser using HTML’s interface. PyScript aims to give users a first-class programming language that has consistent styling rules, is more expressive, and is easier to learn.

Components of PyScript

At that point, you can then use PyScript components in your HTML page. PyScript currently implements the following elements:

  1. py-script: that can be used to define Python code that is executable within the web page. The element itself is not rendered to the page and only used to add logic.

  2. py-repl: creates a REPL component that is rendered to the page as a code editor and allows users to write code that can be executed.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>

<body>
    <py-script>
        print("Hi Welcome to Python test page\n");
        print("Now it will show a calculation");
        print("30+2=");
        print(30+2);
    </py-script>
</body>

</html>

For more details, you can check my article: PyScript - Way to run Python in Web

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHaren SarmaView Question on Stackoverflow
Solution 1 - PythonUku LoskitView Answer on Stackoverflow
Solution 2 - PythonjpaView Answer on Stackoverflow
Solution 3 - PythonAsh UpadhyayView Answer on Stackoverflow
Solution 4 - Pythonrassa45View Answer on Stackoverflow
Solution 5 - Pythonsatyakam shashwatView Answer on Stackoverflow
Solution 6 - PythonMarcoView Answer on Stackoverflow
Solution 7 - PythonUsmanView Answer on Stackoverflow