exec / execfile namespace problem

Gordon McMillan gmcm at hypernet.com
Sat Nov 6 20:58:57 EST 1999

Karan Vasudeva has problems with exec:

> .... my
> problem is, when i call my script from another script (by doing
> an exec, thats what i need to do, you see), the interpreter stops
> at httplib.py as it can't find that socket called self.sock .
> This appears to be a namespace issue. I just want to know how to
> do this right.

exec is pretty much only used when you don't know what 
you'll be running at the time you wrote it. If you know what 
you're running at the time you write it, there's no reason to use 
exec. You probably just want:

  import cool

and maybe:

Many python scripts have the form:
def main():
  # whatever

def otherthing():
  # stuff used by main, or usable by others

if __name__ == '__main__':
  main() # if invoked as a script, run main()
Then they can run as the top level script, or they can be 
imported, and any functions, classes etc. used by the 

- Gordon

More information about the Python-list mailing list