【问题标题】:python error when importing from __init__ file从 __init__ 文件导入时出现 python 错误
【发布时间】:2014-03-13 19:52:15
【问题描述】:

我的站点包目录中安装了一个包。文件夹结构是这样的

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文件导入时会报错??

【问题讨论】:

    标签: python-2.7 python-import


    【解决方案1】:

    在我看来你缺少一些反斜杠

    MyPkg\
      __init__.py
    
      LogUtils\
        __init__.py, \
        logwrapper.py
    
      Shortcuts\
        __init__.py, \
        somefile.py
    

    【讨论】:

      【解决方案2】:

      如您所见,您导入的不是同一个模块:

      >>> from MyPkg import LogUtils
      

      对比

      from LogUtils import logger, log
      

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

      from MyPkg.LogUtils import logger, log
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多