简体   繁体   English

python3上的模块导入不是python2

[英]Module imports on python3 not python2

I have a project with the following file structure: 我有一个具有以下文件结构的项目:

test/
    test.py
    extra/
        stuff.py
        __init.py__

The code for test.py is simply: test.py的代码很简单:

import sys
sys.path.append("/path/to/test")
import extra

This happily runs using python3 test.py , but will not run in python 2.7, and I'm completely stumped having read a lot of questions on the topic. 使用python3 test.py愉快地运行它,但不能在python 2.7中运行,而我已经阅读了很多关于该主题的问题,完全感到困惑。

The error given by python 2.7 is python 2.7给出的错误是

 Traceback (most recent call last):
   File "test.py", line 3, in <module>
    import extra
ImportError: No module named extra

Thanks for the help! 谢谢您的帮助!

This is a copy-paste from: http://python3porting.com/differences.html 这是来自以下 站点 的复制粘贴: http : //python3porting.com/differences.html

In Python 2, if you have a package called mypackage and that contains a module called csv.py, it would hide the csv module from the standard library. 在Python 2中,如果您有一个名为mypackage的软件包,并且包含一个名为csv.py的模块,则它将在标准库中隐藏csv模块。 The code import csv would within mypackage import the local file, and importing from the standard library would become tricky. 代码导入csv将在mypackage中导入本地文件,而从标准库中导入将变得棘手。

In Python 3, this has changed so that import csv would import from the standard library, and to import the local csv.py file you need to write from . 在Python 3中,此更改已更改,因此import csv将从标准库中导入,并导入您需要从中写入的本地csv.py文件。 import csv and from csv import my_csv needs to be changed to from .csv import my_csv. 导入csv和从csv导入my_csv需要更改为从.csv导入my_csv。 These are called “relative imports”, and there is also a syntax to import from one level up module above; 这些称为“相对导入”,还有一种语法可以从上面的一个上级模块导入; from .. import csv. 从..导入CSV

If you to support both Python 2 and Python 3 without 2to3 the from . 如果您同时支持不带2to3的Python 2和Python 3,则from。 and from .. syntax has been available since Python 2.5, together with a from future import absolute_import statement that changes the behavior to the Python 3 behavior. 从Python 2.5开始就可以使用from和..语法,以及将来的 import absolute_import语句(将行为更改为Python 3行为)。

If you need to support Python 2.4 or earlier you have to spell out the whole package name so import csv becomes from mypkg import csv and from csv import my_csv becomes from mypckg.csv import my_csv. 如果您需要支持Python 2.4或更早版本,则必须拼写整个软件包的名称,以便import csv可以从mypkg import csv导入,而csv import my_csv可以从mypckg.csv import my_csv导入。 For clarity and readability I would avoid relative imports if you can and always spell out the whole path. 为了清楚和易读起见,如果可以并始终说明整个路径,我将避免相对引入。

2to3 will check if your imports are local and change them. 2to3将检查您的进口商品是否为本地商品并进行更改。

In short, Python2 allows you to get away with relative imports, python3 doesn't. 简而言之,Python2允许您摆脱相对的进口,而python3 则不允许。

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

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