why _import__ only works from interactive interpreter?

I V wrongbad at gmail.com
Sun May 7 20:17:20 EDT 2006


On Sun, 07 May 2006 16:21:01 -0700, linuxnow at gmail.com wrote:
> So, if this is right, I need to put the .py file to be imported inside
> sys.path!! And the relative path will be usedto find the module.
> 
> Can I __import__ providing the absolute path?

>>> import sys
>>> print sys.path
['', '/usr/lib/python24.zip', '/usr/lib/python2.4',
'/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk',
'/usr/lib/python2.4/lib-dynload',
'/usr/local/lib/python2.4/site-packages',
'/usr/lib/python2.4/site-packages',
'/usr/lib/python2.4/site-packages/HTMLgen',
'/usr/lib/python2.4/site-packages/Numeric',
'/usr/lib/python2.4/site-packages/PIL',
'/usr/lib/python2.4/site-packages/cairo',
'/usr/lib/python2.4/site-packages/gst-0.10',
'/usr/lib/python2.4/site-packages/gtk-2.0',
'/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode',
'/usr/lib/site-python'] 

Compare with:

tim at october:~/src/tests$ cat > test.py
import sys
print sys.path
tim at october:~/src/tests$ python test.py
['/home/tim/src/tests', '/usr/lib/python24.zip', '/usr/lib/python2.4',
'/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk',
'/usr/lib/python2.4/lib-dynload',
'/usr/local/lib/python2.4/site-packages',
'/usr/lib/python2.4/site-packages',
'/usr/lib/python2.4/site-packages/HTMLgen',
'/usr/lib/python2.4/site-packages/Numeric',
'/usr/lib/python2.4/site-packages/PIL',
'/usr/lib/python2.4/site-packages/cairo',
'/usr/lib/python2.4/site-packages/gst-0.10',
'/usr/lib/python2.4/site-packages/gtk-2.0',
'/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode',
'/usr/lib/site-python'] 

Note that the first entry in sys.path when run from the interactive
intepreter is a blank string, which doesn't appear in the output from the
script - I assume that's what is allowing the interactive version to
import via an absolute path. I'm not sure if this is the intended
behavior or a bug.

You could make your script work the same way as the interactive
interpreter by doing:

import sys
sys.path.append('')
mod = __import__('/your/absolute/path/module')

But it might be better to just add the particular path:

sys.path.append('/your/absolute/path')
mod = __import__('module')









More information about the Python-list mailing list