Display a webpage from a Python script

If you just want to display text on a webpage from a Python script, a simple way to print to a web page is shown in the script below:

#!/usr/bin/python

print "Content-type: text/plain\n"
print "Hello world"

If you want to display HTML code, you can use Python code like the following:

#!/usr/bin/python

print "Content-type: text/html"
print
print """<!DOCTYPE HTML>
<html lang="en">
<body>
<h1>Hello World!</h1>
</body>
</html>
"""

In Python, Triple quotes, i.e. """...""" or '''...''' can be used to have string literals span multiple lines, so, in the example above, all of the text following the three double quotes after the third print statement up until the next set of three double quotes will be printed, i.e., displayed on the web page.

You can put the Python code to display the HTML code that appears at the top and bottom of webpages in functions that you can reuse in other scripts as shown below:

#!/usr/bin/python

def htmlTop():
  print "Content-type: text/html"
  print
  print """<!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="utf-8">
  <title>Testing</title>
  </head>
  <body>"""

def htmlBottom():
  print '''</body>\n
  </html>'''

htmlTop()
print "Hello world"
htmlBottom()

You can have single quotes that are part of the HTML code appear within the triple quotes.

Some simple oversights can cause a "500 Internal Server Error" and result in a web server displaying an error message similar to the following one when a Python script is run that should produce a page to be displayed on a website.

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at john.doe@example.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

The error message displayed by the web server will be accompanied by an entry in the web server's log file similar to the one below for an Apache web server:

[Fri Sep 08 16:15:29.149109 2017] [cgi:error] [pid 38686] [client ::1:50621] End of script output before headers: test.py

Some simple things to check include the following:

  1. Check to be sure you have indicated the script is a Python script by placing a line similar to the one below in the script (adjust the line to match the location of the Python executable on the system, which you can determine by issuing the command which python.

    #!/usr/bin/python
  2. Check to be sure that the file permissions are set on the script file so that it will be executable by the web server software, i.e., by the apache account, if you are using Apache as the web server account. You can change the permissions so that all accounts on the system have "execute" privilege for the script with the command chmod +x filename where filename is the name of the script file. E.g., in the case below the script test.py would produce the error message above until execute permission is assigned to the file.

     $ ls -lg test.py
    -rw-r--r--  1 ABC\Domain Users  293 Sep  8 16:20 test.py
    $ chmod +x test.py
    $ ls -lg test.py
    -rwxr-xr-x  1 ABC\Domain Users  293 Sep  8 16:20 test.py
    $

If you get the "Internal Server Error" message rather than seeing the expected web page displayed, you can include the lines below in the Python code to help you debug the problem. They will result in additional details being recorded in the web server's error log.

# enable debugging
import cgitb
cgitb.enable()

E.g., if I omitted the second print command from the htmlTop function's code by commenting it out, so that it looked like the following, I would get the "Internal Server Error" message:

Python by Example
Python by Example
1x1 px

def htmlTop():
  print "Content-type: text/html"
#  print
  print """<!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="utf-8">
  <title>Testing</title>
  </head>
  <body>"""

But I could then look in the webserver's error log file and see an entry like the following one:

[Fri Sep 08 21:37:37.175531 2017] [cgi:error] [pid 83371] [client ::1:53523] malformed header from script 'test.py': Bad header: <!DOCTYPE html>

The coding error may still not be immediately obvious, but in this case it points to exactly where in the code the problem occurs and I can tell that I've omitted printing the blank line after the print "Content-type: text/html" statement.

Related articles:

  1. Running a Python script on an Apache web server
  2. Using Python scripts with Apache on OS X El Capitan
  3. Passing a parameter to a Python script from a web page