How To Insert Python In Your HTML Page

In order for you to include python in your html applications you first need to
have python running on your webserver.

Since most webservers, like Hostgator, are installed with some flavor of Linux, python should already be there.

Hostgator, by the way, was the easiest webhost to get my python scripts up and running on.

All I needed to do was set the permissions of the python file and folder to 755 (chmod 755) (reference the image), and add a htaccess file in the folder (reference the image for the htaccess syntax), which says that it’s ok to run python , .py, files.

All the htaccess file has in it is this:

“Addhandler cgi-script .py”

–> It’s just the text above, but here is the file anyway:

Here is a picture of what my setup looks like (including how to set the file permissions to 755 using FileZilla):

Here’s what the script looks like when it works:

http://pythoninhtmlexamples.com/files/test2.py

#!/usr/bin/python
print "Content-type: text/html\n\n";
print "<html><head>";
print "<title>Python Test</title>";
print "</head><body>";
print "<p>This will print the contents of my Python script</p>";
print "</body></html>"; 

In order to run a python script on your webserver, you are going to have to include “#!/usr/bin/python” on the first row of your script. You basically have to “tell” the webserver that you are about to run a python script, and you want the python interpreter located in the /usr/bin/python directory to interpret the script.

This should be the result of running the script:

It will interpret the script, and not just output the text of the file.

“print” in python does the same thing as “echo” in php, and outputs the content to your screen.

Let me know if you need help.

Facebooktwitterredditpinterestlinkedinmail
Tags: , , ,
Previous Post

Simple Python Variables Examples