dynamically importing a module and function
John Machin
sjmachin at lexicon.net
Mon Apr 21 18:39:00 EDT 2008
rkmr.em at gmail.com wrote:
> Hi
> I have a function data['function'], that I need to import from a file
> data['module'], in the directory data['cwd']
OT: Any good reason for using a dictionary instead of a class instance
(data.functiom, data.module, etc)?
>
> If I do this from python interactive shell (linux fedora core 8) from
> dir /home/mark it works fine:
>
> cwd = data['cwd']
> os.chdir(cwd)
> print os.getcwd()
> module = __import__(data['module'])
> function = getattr(module, data['function'])
>
This is possibly due to python using what was the current working
directory when it started up.
An alternative (untested):
saved = sys.path
sys.path = data['cwd']
module = __import__(data['module'])
sys.path = saved
Exception handling is left as an exercise for the reader.
HTH,
John
More information about the Python-list
mailing list