doted filenames in import statements

Piet van Oostrum piet at cs.uu.nl
Tue Jul 21 18:29:52 EDT 2009


>>>>> Jean-Michel Pichavant <jeanmichel at sequans.com> (JP) wrote:

>JP> Hi fellows,
>JP> I'd like to use the dynamic __import__ statement. It works pretty well with
>JP> non dotted names, but I cannot figure how to make it work with dotted file
>JP> paths.

What is a dotted file path? Is that 4.6.0.0?

>JP> example:

>JP> file = "/home/dsp/test.py"
>JP> test = __import__(file)

>JP> works like a charm

That's not supposed to work. In older pythons it did work but that's a
bug. In newer pythons it doesn't. __import__ works on module names, not
on file names.

Python 2.6:

>>> spam = __import__('/Users/piet/TEMP/test.py', globals(), locals(), [], -1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: Import by filename is not supported.
>>> 

>JP> file = "/home/dsp/4.6.0.0/test.py"
>JP> test = __import__(file)
>JP> => no module name blalalal found.

>JP> Any suggestion ? I tried multiple escape technics without any success.

Rightly so.

I think the best would be to add the directory to sys.path 
sys.path.add('/home/dsp/4.6.0.0')
and then
__import__('test', ... ) 
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list