[Tutor] cgi cross import problem

Lloyd Kvam pythonTutor at venix.com
Thu May 6 10:12:38 EDT 2004

On Thu, 2004-05-06 at 05:57, pan at uchicago.edu wrote:
> I have 2 modules:
> mod1.py
> mod2.py
> Each is used for cgi, so they both start with:
> #!C:\python22\python.exe
> print 'Content-type: text/html'
> print

The python import actually executes the statements it finds in the file
being imported.  You may have seen scripts with the line
if __name__ == '__main__:

This line allows a file to detect if it is being imported or being run. 
__name__ == '__main__' is only true when the file is being run.

To use your cgi script as an importable module, add this if test and fix
your code so that the statements that only pertain to running the script
are only executed when it is actually run and not simply imported.

if __name__ == '__main__:
	print 'Content-type: text/html'

It is often preferable to package the "run part" into a function and
only call that function when the file is run.

> And they both perform cgi function normally. 
> Now, in mod2, I want to use the classes in mod1, so in mod2 I added:
> import mod1
> Unfortunately, this import results in a 'Content-type: text/html'
> showing up as the first line on the webpage when calling mod2.py. 
> I tried to import only the class I need:
> from mod1 import MyClass
> But the 'Content-type: text/html' still shows up.
> Can I avoid this in any way??? 
> (certainly, I want both mod1 and mod2 able to perform cgi normally)
> thx in advance.
> pan
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582

More information about the Tutor mailing list