execfile environment??

Ype Kingma ykingma at accessforall.nl
Tue Aug 7 15:47:28 EDT 2001


Jason,

you wrote:
> 
> I am trying to call a module with the execfile function. Is there a way to
> specify the paths to search for the module I am calling?
> For example:
> 
> def call_module(module_name):
>         # addition checks required before executing
>                 print "Executing "+module_name
>                 execfile(module_name)
> 
> When I call this function, I want it to find "module_name", i.e testing.py,
> within the sys.path. Is this possible, or do I have to include the entire path
> of module_name when using execfile??

You need the full path name for execfile().
I don't know whether it also works relative to the working directory
of the interpreter.

This means you can do evt. sys.path searching yourself.
It's quite straightforward with the os module.

The call_module() name might be a bit confusing. And since 
you are talking about execfile environment, consider the following:
- the module will run in the globals/locals passed to execfile, or the 
  globals/locals active at the execfile call, so
  in case you want __name__ to be set to sth
  like '__main__' you'll have to provide this in a
  (freshly copied) dictionary argument to execfile().
- already loaded modules will not be reloaded (sys.modules).
- sys.argv is not affected by execfile().
You can control all of these.
Evt. use try/finally to restore the sys.* things to their previous value
as needed.
Finally you might want to catch all exceptions
thrown by execfile(), and interpret or return sys.exc_info().

As long as exceptions are not guaranteed to be subclasses of Exception,
you might use sth like:

try:
   execfile(...)
except Exception, e:
   # do what you think needs to be done.
except:
   # deprecated exception caught: inform the user of lost karma points.
 
Have fun,
Ype

-- 
email at xs4all.nl



More information about the Python-list mailing list