我在 spyder 中有一个 python 项目,无论身在何处,我都可以使用它,这意味着我可以在一天之内打开它并在 Mac、Windows 和 Ubuntu 上使用它。问题是导入模块在 Windows 上永远无法正常工作。
我的文件系统设置如下:
- /Project
* Main.py
- /modules
* Functions.py
* constants.py
* otherFunctions.py
- /Data
* bunch of data files
在 Main.py 中,我有:
import modules.Functions as gf
import modules.otherFunctions as of
from modules.constants import gas_const_R, Solar_const
在 otherFunctions.py 中,我有:
import modules.Functions as gf
在 constants.py 中,我有:
gas_const_R = 287.04
Solar_const = 1368.0
这一切在 Linux 和 Mac 上都能完美运行,但 Windows 不会导入常量,也不会让 otherFunctions.py 导入 Functions.py。
当前工作目录在所有操作系统上都是相同的。 Main.py可以导入所有模块,但是在windows下不能互相导入,我在windows下获取不到常量。
这是我的 spyder 设置的问题吗? 是windows路径的问题吗? 有没有一种方法可以根据我使用的操作系统进行不同的导入?
请您参考如下方法:
这取决于您的 IDE 如何执行您的程序,特别是您的 CWD(当前工作目录)是什么。那是(某些)进口相对于的地方。你可以通过运行来检查这个目录是什么:
import os
print(os.path.abspath('.')
对于您想要的行为,这应该打印所有三个目录的父目录。如果没有,则必须更改 IDE 的设置(抱歉,我不知道 spyder)。
