假设我有这样的目录结构:
- 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覆盖了我的utils.py。但这对我来说似乎没有意义。
classes.py 和 utils.py 的完整源代码可以在这里找到(如果它有助于发现问题所在):https://github.com/goFrendiAsgard/feature-extractor
最佳答案
将下面提到的行添加到位于论文文件夹之外的测试文件中。
导入sys
sys.path.insert(0,"/论文文件夹/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)
关于python - 从包外部导入 python 模块会产生意外的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547841/