其他答案几乎正确
Python 3:
import sys
import_paths = sys.path
在 Python 2.7 中:
import sys
import os
import copy
import_paths = copy.copy(sys.path)
if '__file__' in vars(): import_paths.append(os.path.abspath(os.path.join(__file__,'..')))
在这两个版本中,主文件(即__name__ == '__main' 是True)会自动将自己的目录添加到 sys.path。 然而 Python 3 只从sys.path 导入模块。 Python 2.7 从sys.path 和当前文件的目录导入模块。当您具有以下文件结构时,这是相关的:
|-- start.py
|-- first_import
| |-- __init__.py
| |-- second_import.py
内容
start.py:
import first_import
__init__.py:
import second_import.py
在 Python 3 中直接运行 __init__.py 会起作用,但是当你运行 start.py 时,__init__.py 将无法运行 import second_import.py,因为它不会在 sys.path 中。
在 Python 2.7 中,当您运行 start.py 时,__init__.py 将能够 import second_import.py,即使它不在 sys.path 中,因为它与它在同一个文件夹中。
不幸的是,我想不出一种方法来完美地在 Python 3 中复制 Python 2.7 的行为。