2016-03-22 23 views
0

我一直與學習Python的硬道理,而我從導入不同的目錄模塊又卡在實施例48例47,我不得不創建一個看起來像這樣的目錄:附加PYTHONPATH,在Windows

skeleton 
|--ex47 
    |--module.py 
    |--__init__.py 
|--tests 
    |--ex47_tests.py 
    |--__init__.py 

從現在開始,我不得不將ex47/module.py導入到tests/ex47_tests.py中。我收到了'No module named ex47'錯誤。對於這個問題的解決方案是通過增加兩行代碼到module.py添加ex47目錄站點包的路徑:

import sys 
sys.path.append('./ex47') 

這工作得很好。我可以將module.py導入到ex47_tests.py中,並且可以將其導入到我的計算機上的任何位置。

移動到示例48後,我創建了完全相同的目錄,文件,我添加了ex48 /的路徑,並且我一直收到'No module named 48'。我搜索了不同的解決方案,他們都沒有工作。將__init__.py添加到骨架中並沒有幫助。

這個問題是超級基礎問題,但它沒有引入到新的python程序員。順便說一句,我想要一個解決方案,可以在任何計算機上使用我的代碼。

這樣的問題是否發生在Linux?

回答

3

所有你需要看到的是你從哪裏調用python程序。 我有以下文件。

C:\Users\kumarvivek\Desktop>tree /f skeleton 
Folder PATH listing for volume ???? 
Volume serial number is 6AE1-4919 
C:\USERS\KUMARVIVEK\DESKTOP\SKELETON 
│ __init__.py 
│ 
├───ex47 
│  mod.py 
│  mod.pyc 
│  __init__.py 
│  __init__.pyc 
│ 
└───tests 
     ex47_tests.py 
     __init__.py 


C:\Users\kumarvivek\Desktop> 

具有以下內容:

C:\Users\kumarvivek\Desktop>type skeleton\ex47\mod.py 
import os 
x = "C:\\Users\\kumarvivek\\Desktop\\skeleton\\ex47\\module.py" 
directoryPath= os.path.dirname(x) 
fileName = os.path.basename(x) 
print "\nFilePath:  %s\nDirectoryPath: %s\nFileName:  %s\n" %(x, directo 
ryPath, fileName) 
C:\Users\kumarvivek\Desktop> 

而且

import sys 

# If the Current Working directory is skeleton 
# C:\Users\kumarvivek\Desktop\skeleton>python C:\Users\kumarvivek\Desktop\skeleton\tests\ex47_tests.py 
# 
# sys.path.append(r"..\skeleton") 

# If the Current Working directory is any of these "tests" or "ex47" 
# C:\Users\kumarvivek\Desktop\skeleton\tests>python C:\Users\kumarvivek\Desktop\skeleton\tests\ex47_tests.py 
# C:\Users\kumarvivek\Desktop\skeleton\ex47> 
# 
# sys.path.append(r"..\..\skeleton") 

sys.path.append(r"..\..\skeleton") 


from ex47 import mod 

print mod.x , mod.directoryPath, mod.fileName 
+0

運作良好。非常感謝。 – oshiri