假设我有这样的目录结构:
- Documents/
- thesis_program/
- __init__.py
- classes.py
- utils.py
- GE_Test.py
- GE_Test_fail.py
classes.py和utils.py包含一些类和函数。 除导入部分外,GE_Test.py和GE_Test_fail.py包含完全相同的代码。 在 GE_Test.py 中,我以这种方式导入类和实用程序:
from utils import execute
from classes import Grammatical_Evolution
在 GE_Test_fail.py 中,我以这种方式导入类和实用程序:
from thesis_program.utils import execute
from thesis_program.classes import Grammatical_Evolution
出乎意料的是,我得到了不同的结果。这里有什么不对吗? 我是否正确导入模块?
我可以确保结果应该相同,因为我使用某个种子生成随机数
此外,classes.py以某种方式依赖于utils.py,因为我在utils.py中有几个常用函数。我怀疑utils也是系统使用的名称。所以在第二种情况下(GE_Test_fail.py)系统工具覆盖我的utils.py。但这似乎对我没有意义。
这里提供了classes.py和utils.py的完整源代码(如果它有助于发现错误):https://github.com/goFrendiAsgard/feature-extractor
答案 0 :(得分:2)
将以下提到的行添加到您的论文文件夹之外的测试文件中。
import sys
sys.path.insert(0,"/path to your thesis folder/thesis_program")
并保持其他一切;例如在GE_Test.py
..
import sys
sys.path.insert(0,"/path to your thesis folder/thesis_program")
from utils import execute
from classes import Grammatical_Evolution
修改强>
或使用此功能使其更具动态性
(警告:不要试图通过os.path.abspath('./thesis_program')
查找路径,因为您可能无法始终发现test_files
和thesis_folder
位于同一个目录中;如果您可以修复它们永久地存储在您的代码中;然后您可以在系统的任何位置自由使用它们)
import os, sys
lib_path = os.path.abspath('./thesis_program')
sys.path.insert(0,lib_path)