77

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 the executed Python script. Instead, it showed the above code as HTML. Where is the problem? How can I run a Python file in a web page?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Haren Sarma
  • 2,267
  • 6
  • 43
  • 72
  • 9
    this is python not php, you have to setup python web framework e,g, webpy or django etc, and configure appache with mod_python. – Aamir Rind Sep 18 '11 at 10:43
  • 1
    try whisky!! :D "WSGI"(Web server Gateway interface) . – Arunmu Sep 18 '11 at 13:21
  • 2
    It is possible to run Python in a web page (on the client side) using frameworks such as Pyjamas and Skulpt. – Anderson Green Dec 12 '12 at 20:29
  • 17
    Why do you have semicolons? That's used in Java, not Python – rassa45 Dec 11 '15 at 03:52
  • If CGI / server sided python execution is not what you ale looking for, see : http://www.skulpt.org/ - this appears to execute python in the browser. – Lord Loh. Apr 20 '18 at 04:59
  • Such a moving question – Adrien Renaud Jun 05 '18 at 17:47
  • 1
    @rassa45: [Sometimes](https://stackoverflow.com/a/29094034): *"...the use of the semicolon to suppress not desired output in the interpreter has become more relevant following the introduction of the IPython notebook, that permits to save the input and the output, including graphical output, of an interpreter session for documentation and eventual reuse."* – Peter Mortensen Jun 02 '22 at 00:01
  • Related: *[What is the difference between semicolons in JavaScript and in Python?](https://stackoverflow.com/questions/7219541/)* – Peter Mortensen Jun 02 '22 at 00:06

6 Answers6

56

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.

lvc
  • 34,233
  • 10
  • 73
  • 98
Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
  • 2
    In this day and age, CGI is becoming more and more of a dinosaur. If you are familiar with CGI, by all means use it; but if you are only just starting, finding a simple framework is probably the path of least resistance in terms of being able to get help from others and Google. – tripleee Jan 11 '19 at 06:12
25

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.

jpa
  • 10,351
  • 1
  • 28
  • 45
  • 3
    For the web hosting I'm using, I had to add `#!/usr/bin/env python # -*- coding: UTF-8 -*-` instead. – GrandAdmiral Feb 02 '13 at 23:47
  • My browser just tries to download the CGI file instead of the server executing it. Permissions are 755. – posfan12 Jun 08 '18 at 23:03
  • 2
    Calling the file `index.cgi` instead of `index.py` is probably misdirected. Call it whatever you like -- the important thing is to configure the web server to understand that it's a CGI script rather than static content. – tripleee Jan 11 '19 at 06:13
  • 2
    A much better answer to the actual question than the accepted one – blissweb May 01 '20 at 11:50
19

Using the 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 strings and which can be easily changed to suit your requirements.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ash Upadhyay
  • 1,796
  • 2
  • 15
  • 20
9

If you are using your own computer, install a software called XAMPP (or WAMP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to the xampp folder and double click the htdocs folder. Now you need to create an HTML file (I'm going to 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"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rassa45
  • 3,482
  • 1
  • 29
  • 43
3

Well, the 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:

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marco
  • 2,757
  • 1
  • 19
  • 24
  • 5
    There are quite a few Python-in-the-browser technologies out there, here's a useful table summarising quite a few: http://stromberg.dnsalias.org/~strombrg/pybrowser/python-browser.html Here's a blog post (written by me) that goes into some detail about six that all work differently (including Skulpt): https://pythontips.com/2019/05/22/running-python-in-the-browser/ – Shaun Taylor Aug 29 '19 at 13:12
0

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 file, and you will see what you want.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    This is sort of the opposite to what OP is asking. They want a webpage which can run a Python script: this is a Python script which will create a webpage. It will do the job, but I don't think this can be made into a dynamic webpage. – Lou Oct 20 '20 at 11:55