0

我在以下目录结构中有一个 2.6 python 脚本和库:

+ bin
\- foo.py
+ lib
\+ foo
 \- bar.py

我希望用户运行bin/foo.py以实例化lib/foo.py. 为此,在我的bin/foo.py脚本中,我有以下代码:

from __future__ import absolute_import
import foo
klass = foo.bar.Klass()

但是,这会导致:

AttributeError: 'module' object has no attribute 'bar'

即它认为这foo是它本身而不是库foo- 重命名bin/foo.pybin/foo-script.py按预期工作。

有没有办法可以保留bin/foo.py脚本并导入lib/foo.py

4

2 回答 2

2

默认情况下,当前目录位于路径上,因此您需要在导入其他foo模块之前将其删除:

import sys
sys.path = [dir for dir in sys.path if dir != '']

或者,在目录前面添加lib优先级:

import sys
sys.path = ['../lib'] + sys.path
于 2013-01-24T19:51:37.000 回答
0

If you just write import foo, it will definitely load the foo module in the current scope. Assuming lib and foo as packages, won't you need to write something like this in order to make it work?

import lib.foo.bar as foobar
klass = foobar.Klass()
于 2013-01-24T19:57:06.087 回答