Haren Sarma
Haren Sarma

Reputation: 2553

How to run a Python script in a web page

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?

Upvotes: 79

Views: 356607

Answers (6)

Marco
Marco

Reputation: 2922

In case someone 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.

Upvotes: 3

satyakam shashwat
satyakam shashwat

Reputation: 80

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.

Upvotes: -1

rassa45
rassa45

Reputation: 3560

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"

Upvotes: 9

Ash Upadhyay
Ash Upadhyay

Reputation: 1966

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.

Upvotes: 20

Uku Loskit
Uku Loskit

Reputation: 42050

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.

Upvotes: 57

jpa
jpa

Reputation: 12176

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.

Upvotes: 25

Related Questions