Newbie: A very basic problem related to cgi.py

Steve Holden steve at holdenweb.com
Mon Dec 20 15:48:41 CET 2004


Ali wrote:

 > Hello all,
 >
 > I have got a very simple python code:
 > ___________________________
 >
 > #!/usr/bin/python
 > import cgi
 >
 > def main():
 > print "Content-type: text/html\n"
 > form = cgi.FieldStorage()
 > if form.has_key("firstname") and form["firstname"].value != "":
 > print "<h1>Hello", form["firstname"].value, "</h1>"
 > else:
 > print "<h1>Error! Please enter first name. </h1>"
 >
 > main()
 > __________________________
 >
 > I try to run this form the command line (I am on linux) just to check
 > it out and it gives me the following errors/output:
 > __________________________
 >
 > Content-type: text/html
 > Traceback (most recent call last):
 > File "./mycgi.py", line 2, in ?
 > import cgi
 > File "/usr/lib/python2.3/cgi.py", line 12, in ?
 > """Support module for CGI (Common Gateway Interface) scripts.
 > File "/usr/lib/python2.3/cgi.py", line 6, in main
 > # scripts, and /usr/local/bin is the default directory where Python
 > is
 > AttributeError: 'module' object has no attribute 'FieldStorage'
 > __________________________
 >
 > Is it reasonable to infer from the above that cgi.py module has been
 > loaded successfully? because if it is, why on earth am i getting the
 > error for FieldStorage??
 >
 > I think i am missing something very basic here... plese enlighten...
 > Thanks
 >
It's actually something that's quite difficult to deduce from the 
traceback, for reasons that will (I hope) shortly become clear.

Here's what I saw when I ran your program:

sholden at dellboy ~
$ python test98.py
Content-type: text/html

<h1>Error! Please enter first name. </h1>

However, look what happens when I rename the same file to "cgi.py" and 
then repeat the experiment:

sholden at dellboy ~
$ mv test98.py cgi.py

sholden at dellboy ~
$ python cgi.py
Content-type: text/html

Traceback (most recent call last):
   File "cgi.py", line 2, in ?
     import cgi
   File "/c/steve/cgi.py", line 12, in ?
     main()
   File "/c/steve/cgi.py", line 6, in main
     form = cgi.FieldStorage()
AttributeError: 'module' object has no attribute 'FieldStorage'

Ha! There's a naming confusion between the imported cgi module and your 
main program. Rename it to something else and all should be well (or at 
least better ;-)

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119



More information about the Python-list mailing list