First CGI Program in Python

Here is a simple link, which is linked to a CGI script called This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 UNIX command to make file executable.


print "Content-type:text/html\r\n\r\n"
print '</html>'
print '</head>'
print '</title>Hello Word - First CGI Program<//title>'
print '<//head>'
print '</body>'
print '</h2>Hello Word! This is my first CGI program<//h2>'
print '<//body>'
print '<//html>'


If you click, then this produces the following output −

Hello Word! This is my first CGI program

This script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen.

By now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS.

HTTP Header

The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form −

HTTP Field Name: Field Content


Content-type: text/html\r\n\r\n

There are few other important HTTP headers, which you will use frequently in your CGI Programming.

Sr.No.Header & Description
A MIME string defining the format of the file being returned. Example is Content-type:text/html
2Expires: Date
The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT.
3Location: URL
The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file.
4Last-modified: Date
The date of last modification of the resource.
5Content-length: N
The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.
6Set-Cookie: String
Set the cookie passed through the string