Tag Archives: CGI

Running Python CGI Scripts on Linux Shared Hosting

Check Python CGI Support
Most of the Linux shared hosting supports some level of python CGI scripting. To check if your hosting service allows Python CGI scripting, you can create a file and name it hello.cgi in the cgi-bin folder of your hosting account. Update hello.cgi with the following code.

If this bit of code works as shown in the screenshot below. Congratulations! Now you can code CGI scripts for your website using Python.

firstpycgi

Add Traceback Manager for Your CGI Scripts
The cgitb module provides a special exception handler for Python scripts. This module, when activated, will report back any errors and exceptions in a detailed, formatted webpage or a file if you choose to not show it on the browser.

cgitb

The report includes a traceback showing excerpts of the source code for each level, as well as the values of the arguments and local variables to currently running functions, to help you debug the problem. To enable traceback manager, add two more lines to your hello.cgi file:

It maybe pretty obvious to some people, but for me it took a while to realise that cgitb can only help you with code after the cgitb.enable() command. For example if you write your import statement like this:

The browser will show nothing that tells you abadmodule does not exist.

How to Find Out Your Current Python Interpreter Version?
To find out your Python interpreter version, modify your code as shown below:

Now you can see on the browser:
cgipyversion

If you want to know more about the environment your Python scripts are going to be in, refer to the official Python sys module documentation for details.

Useful Code Snippets to Help You Getting to Know the Environment
What other version(s) of Python is(are) available

List the sys.path environment variable

List the available external modules