为什么这个绝对导入不能用于Python?

时间:2011-02-01 16:17:48

标签: python import python-2.6

我有两个Python 2.6文件,/code/x/X.py

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

...和/code/y/logging.py

from __future__ import absolute_import
import logging as _logging

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

运行X.py打印:

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'>

为什么from __future__ import absolute_import强制import logging导入是绝对导入而不是本地导入?换句话说,为什么我看不到系统日志记录模块?

1 个答案:

答案 0 :(得分:3)

问题原来是imp.load_source命令。第一个参数是它注册模块的名称,后续导入将在查看路径之前首先查看已加载的模块。更改行以使用其他名称,例如:

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

...解决了这个问题。