dynamically importing a module and function
rkmr.em at gmail.com
rkmr.em at gmail.com
Mon Apr 21 18:59:33 EDT 2008
On Mon, Apr 21, 2008 at 3:39 PM, John Machin <sjmachin at lexicon.net> wrote:
> rkmr.em at gmail.com wrote:
> > 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)?
not really, i just wanted to stick to primitive python data types.
> > 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'])
> >
> >
> saved = sys.path
> sys.path = data['cwd']
> module = __import__(data['module'])
> sys.path = saved
now the module gets loaded, but i am not able to get the function from
the module, though it works fine in the interactive-shell
Traceback (most recent call last):
File "/home/mark/work/common/funcq.py", line 62, in <module>
if __name__ == '__main__':do()
File "/home/mark/work/common/funcq.py", line 35, in do
function = getattr(module, data['function'])
AttributeError: 'module' object has no attribute 'new'
this works in shell though..
>>> import os
>>> os.chdir('/home/mark/work/proj1')
>>> import sys
>>> sys.path.append('/home/mark/work/proj1')
>>> module = __import__('app')
>>> function = getattr(module, 'new')
>>> function(1)
1
More information about the Python-list
mailing list