簡體   English   中英

從包外部導入 python 模塊會產生意外行為

[英]importing python module from outside the package produce unexpected behavior

假設我有這樣一個目錄結構:

 - 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

還有截圖: https : //picasaweb.google.com/111207164087437537257/November25201204?authuser=0&authkey=Gv1sRgCOKxot2a2fTtlAE&feat=directlink

將下面提到的行添加到您的論文文件夾之外的測試文件中。

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_filesthesis_folder位於同一目錄中;如果您可以修復它們像上面一樣永久保存在您的代碼中;然后您可以在系統的任何地方自由使用它們)

import os, sys
lib_path = os.path.abspath('./thesis_program')
sys.path.insert(0,lib_path)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM