简体   繁体   English

Python导入可在2.7中使用,但在3.2+中将失败

[英]Python import works in 2.7 but fails in 3.2+

Importing a package with: 导入软件包:

from unique_upload import unique_file_upload

Works in Python 2.7 but fails in Python 3.2 and above with: 可在Python 2.7中使用,但在Python 3.2及更高版本中无法使用:

ImportError: cannot import name unique_file_upload

The project structure is: 项目结构为:

test/ 
   __init__.py
   test_unique_upload # <-- calling from unique_upload import unique_file_upload here

 unique_upload/ 
      __init__.py
      unique_upload

unique_upload/__init__.py contains: unique_upload/__init__.py包含:

__version__ = '0.2.0'
from unique_upload import unique_file_upload

Full stack trace: 完整堆栈跟踪:

ImportError: Failed to import test module: test_unqiue_upload
Traceback (most recent call last):
  File "/opt/python/3.5.0/lib/python3.5/unittest/loader.py", line 428, in _find_test_path
    module = self._get_module_from_name(name)
  File "/opt/python/3.5.0/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name
    __import__(name)
  File "/home/travis/build/agconti/django-unique-upload/test/test_unqiue_upload.py", line 4, in <module>
    from unique_upload import unique_file_upload
  File "/home/travis/build/agconti/django-unique-upload/unique_upload/__init__.py", line 2, in <module>
    from unique_upload import unique_file_upload
ImportError: cannot import name 'unique_file_upload'

Any idea why this is happening? 知道为什么会这样吗?

It seems you are facing one of the incompatible change of Python: Relative imports , aka PEP 328. 看来您正在面对Python的一项不兼容的更改: 相对导入 (aka PEP 328)。

This should work: 这应该工作:

from .unique_upload import unique_file_upload

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM