The Tutorial:

    Lesson 1: The Basics

    Please, read the FAQ before starting.

    This tutorial assumes that you (or your system administrators) have installed a Web server and the Python interpreter correctly. For more information on these topics, check your Web server documentation and the Python Language Website.  Once you have the server and interpreter up and running, the following simple CGI program serves as a good test.

    • Copy the program text from the gray box below and save it in ASCII text format as "example_1.1.cgi".
    • Place the file in your CGI directory ( /cgi-bin/ on most Unix machines).
    • For Unix/Linux users, be sure to change the permissions to make the script executable (chmod +x example_1.1.cgi).
    • Open your Web browser, and type the URL path to the file (i.e., http://your_url_here/cgi-bin/example_1.1.cgi)
    • To generate output to compare your results against, click the button below.

    Code Example 1.1: 

    # Required header that tells the browser how to render the text.
    print "Content-Type: text/plain\n\n"

    # Print a simple message to the display window.
    print "Hello, World!\n"

    So, what do the parts of this file mean?  Let's look at the code line by line.

    Technically, the first line is a comment, as are all lines that begin with a ' # ' in Python.  This comment is special because it tells the Unix/Linux systems where to locate the Python interpreter, which in turn runs the rest of the code file.  Unix/Linux users should verify that this is the correct path to their interpreter.  On other platforms, the operating system locates the interpreter by different methods, and the Python interpreter ignores the first line [1, 2: 14].

    The second line of text is another comment ignored by the interpreter - this time intended for the human reader.  It explains the purpose of the following print statement.  The third line prints a text message to standard output.  This message, "Content-Type: text/plain\n\n", tells the Web browser what type of information follows.  It is specific just to CGI programming.  Note that there are two new-line escape characters, "\n\n".  This "\n" character works like pressing the "Enter" key on a keyboard.  Since most browsers expect a blank line after the content type, the double "\n" works like pressing the "Enter" key twice to create a blank line before the next print statement [1].

    The fourth line, another comment to the reader, explains that the next line of code will print to the window. The final line prints the text message "Hello, World!\n" to standard output. This time the browser knows how to display the text and prints it to the window area [1].

    To Lesson 2 ...

 © 2000 Department of Computer Science, University of Virginia