模块内部文件的导入在python2&中给出了ImportError。适用于python3

时间:2015-04-27 22:08:11

标签: python python-3.x importerror python-2.x

如果我有一些文件' needy'在我的模块'模块',它试图访问' utils'在同一个'模块中。在里面'有需要':

from module.utils import fly    # Works in python3

from utils import fly           # Works in python2

实施例

python/pulla git:(master) ✗ ± pulla
Traceback (most recent call last):
  File "/usr/local/bin/pulla", line 9, in <module>
    load_entry_point('Pulla==0.0.5', 'console_scripts', 'pulla')()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 357, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2394, in load_entry_point
    return ep.load()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2108, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "/Library/Python/2.7/site-packages/pulla/main.py", line 9, in <module>
    from pulla.pulla import Pulla
  File "/Library/Python/2.7/site-packages/pulla/pulla.py", line 5, in <module>
    from pulla.utils import is_this_a_git_dir
ImportError: No module named utils

使用python3作为可执行文件时,导入工作正常。

这也可以在python2的命令行中运行得很好(类似于python3)。

python/pulla git:(master) ✗ ± python2.7
Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pulla
>>> import pulla.utils
>>> from pulla.utils import is_this_a_git_dir
>>> is_this_a_git_dir('.')
True

此特定导入的代码为here on github

1 个答案:

答案 0 :(得分:0)

这听起来像隐含的相对导入。如果你的模块有

from __future__ import absolute_import

在顶部,这将强制导入被解释为绝对导入,因此它正在utils上寻找sys.path模块,而不是找到它。所以你得到ImportError

嗯,我在你的代码中看不到。但无论如何,如果您仍希望导入为相对导入,则可以将其替换为

from .utils import fly

这是一个显式的包相对导入。

Lots of information about absolute vs relative imports