1. Home
  2. Computing & Technology
  3. Python

Creating HTML and XHTML Pages in Python - With and Without CGI

From , former About.com Guide

5 of 6

Feeding Options From the Command Line

As you know from reading Jennifer Kyrnin's tutorial on CGI, every CGI script should be executable from the command line. We should be able to feed some options at the command line and have them appear in the output.

To do this, one need only add string format operators to the output as needed. If, for example, you wanted to automate a welcome statement at the head of the form generated in part 2 of this tutorial, The script could look like this:

import sys name = sys.argv[1] print '''
content-type: text/html

<html>
<head>
<title> This is the title </title>
</head>
<body>
<br>
'''
print "Welcome to %s's Addressbook Entry Page!" %(name)
print '''
<form action="./test.cgi" method="post">
<p> Name: <input type="text" name="name" id="name" value=""/></p>
<p> Street Address: <input type="text" name="st_address" id="st_address" value=""/></p>
# [more address items go here]
<p> Website: <input type="text" name="website" id="website" value=""/></p>
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
'''

The sys module enables the program to interact with the system, here we need it to access the options at the command line. We then assign the value to the variable 'name'. Within the output, we break out of the verbatim output just long enough to print a line with the variable. Then we resume and finish the page.

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Web Development
  5. Python and HTML - Creating HTML and XHTML Pages in Python - Passing Python Options From the Command Line

©2009 About.com, a part of The New York Times Company.

All rights reserved.