从__init__文件导入时出现python错误

时间:2014-03-13 19:52:15

标签: python-2.7 python-import

我的网站包dir中安装了一个软件包。文件夹结构如下所示

MyPkg\
  __init__.py

  LogUtils\
    __init__.py
    logwrapper.py

  Shortcuts\
    __init__.py  <-----this references LogUtils
    somefile.py

当我help ('modules')时,我看到列出了MyPkg。但是我在IDLE中遇到以下错误:

>>> import MyPkg
>>> from MyPkg import LogUtils
>>> from MyPkg import Shortcuts

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    from MyPkg import Shortcuts
  File "C:\Python27\lib\site-packages\MyPkg\Shortcuts\__init__.py", line 1, in <module>
    from GoToUrl import go_to_url
  File "C:\Python27\lib\site-packages\MyPkg\Shortcuts\GoToUrl.py", line 1, in <module>
    from LogUtils import logger, log
ImportError: No module named LogUtils

为什么LogUtils会单独导入精细数据,但是在通过init文件导入时会抛出错误?

2 个答案:

答案 0 :(得分:1)

对我来说,你缺少一些反斜杠

MyPkg\
  __init__.py

  LogUtils\
    __init__.py, \
    logwrapper.py

  Shortcuts\
    __init__.py, \
    somefile.py

答案 1 :(得分:0)

如您所见,您没有导入相同的模块:

>>> from MyPkg import LogUtils

VS

from LogUtils import logger, log

第一个导入名为MyPkg.LogUtils的包,第二个导入名为LogUtils的包。它们是否存在取决于你的python路径,但一般来说,如果第一个工作,将第二个改为

from MyPkg.LogUtils import logger, log