Python 2.x 与 3.x 导入,取决于脚本来自 called/imported 的位置
Python 2.x vs 3.x imports, depending on where script is called/imported from
这可能是关于 Python 2.x 和 3.x 之间导入差异的第 1000 个问题,但对于我的特定 problem/case 我在阅读大部分内容后仍然卡住了他们。考虑这个简单的例子:
目录结构:
main.py
src/
thermo.py
constants.py
__init__.py # empty
main.py:
import src.thermo as thermo
thermo.calc_thermo()
src/thermo.py:
from constants import cp
def calc_thermo():
print(2*cp)
if __name__ == '__main__':
# Just for testing `thermo.py`
calc_thermo()
src/constants.py:
cp = 1234.
现在,我想使用两种方式thermo.py
;直接从 src/
子目录(对于此特定文件的 debugging/unit-testing/..)调用它,或者通过将其导入 main.py
作为整个程序的一部分。对于上面的示例,这一切都适用于 Python 2.7,在 Python3.x 我可以从 src/
目录调用 thermo.py
,但导入 thermo
从 main.py
导入 constants
.
失败
SO 上有很多类似的问题,大多数建议通过相对导入解决此问题,即将 thermo.py
从:
更改
from constants import cp
至
from .constants import cp
现在如果我调用 main.py
就可以了,但是我无法直接从 src/
目录调用 thermo.py
!如何最好地解决这个问题,即创造从其父目录 (main.py
) 导入 thermo.py
的可能性,同时保持直接从 [=21= 调用 thermo.py
的可能性]?
设置环境变量 PYTHONPATH
以包含您的 src
目录(当然是它的绝对路径)应该可以从任何目录导入。
必须在启动 Python 解释器之前设置此环境变量。
这可能是关于 Python 2.x 和 3.x 之间导入差异的第 1000 个问题,但对于我的特定 problem/case 我在阅读大部分内容后仍然卡住了他们。考虑这个简单的例子:
目录结构:
main.py
src/
thermo.py
constants.py
__init__.py # empty
main.py:
import src.thermo as thermo
thermo.calc_thermo()
src/thermo.py:
from constants import cp
def calc_thermo():
print(2*cp)
if __name__ == '__main__':
# Just for testing `thermo.py`
calc_thermo()
src/constants.py:
cp = 1234.
现在,我想使用两种方式thermo.py
;直接从 src/
子目录(对于此特定文件的 debugging/unit-testing/..)调用它,或者通过将其导入 main.py
作为整个程序的一部分。对于上面的示例,这一切都适用于 Python 2.7,在 Python3.x 我可以从 src/
目录调用 thermo.py
,但导入 thermo
从 main.py
导入 constants
.
SO 上有很多类似的问题,大多数建议通过相对导入解决此问题,即将 thermo.py
从:
from constants import cp
至
from .constants import cp
现在如果我调用 main.py
就可以了,但是我无法直接从 src/
目录调用 thermo.py
!如何最好地解决这个问题,即创造从其父目录 (main.py
) 导入 thermo.py
的可能性,同时保持直接从 [=21= 调用 thermo.py
的可能性]?
设置环境变量 PYTHONPATH
以包含您的 src
目录(当然是它的绝对路径)应该可以从任何目录导入。
必须在启动 Python 解释器之前设置此环境变量。