开发者

Why doesn't this absolute import work in Python?

I've got two Python 2.6 files, /code/x/开发者_运维技巧X.py:

import imp
print 'running'
logging = imp.load_source('logging', '/code/y/logging.py')

... and /code/y/logging.py:

from __future__ import absolute_import
import logging as _logging

import sys, os
print sys.path
print os.getcwd()
print _logging

Running X.py prints:

running
['/code/x', '/usr/lib/pymodules/python2.6', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/plat-linux2', '/usr/local/lib/python2.6/dist-packages']
/code/x
<module 'logging' from '/code/y/logging.py'>

Why doesn't the from __future__ import absolute_import force the import logging import to be an absolute one, instead of a local one? In other words, why don't I see the system logging module?


The issue turns out to be the imp.load_source command. The first argument is the name it registers the module under, and subsequent imports will first look in the loaded modules before looking in the path. Changing the line to use a different name, like:

logging = imp.load_source('logx', '/code/y/logging.py')

... fixes the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜