2016-11-18 37 views
3

我已經搜索了一段時間來找到解決此問題的方法,但已經幹了。我希望我能在這裏找到一些幫助。正如標題所示,python無法識別已在我的PYTHONPATH中設置的模塊。Python無法識別由PYTHONPATH設置的模塊

我目前正在對具有下列整體結構的一個項目:

base 
├── util 
│   └── logging_utility.py 
└── project 
    └── app 
     ├── config.py 
     └── runner.py 

這是在Python 3.5通過所謂venv_1虛擬環境中執行。我使用運行El Capitan的Mac。

runner.py腳本中使用下面的import語句調用logging_utility

執行的時候,我收到此錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: No module named 'util.logging_utility' 

我從base級目錄的終端運行此。我使用下面的命令來調用腳本:

PYTHONPATH=$HOME/base VIRTUAL_ENV=$HOME/.virtualenvs/venv_1 PATH=$VIRTUAL_ENV/bin:$PATH $HOME/.virtualenvs/venv_1/bin/python -- project/app/runner.py 

現在,我已經嘗試通過打印出我的env以及sys.path調試此。在這兩種情況下,base目錄都顯示在路徑中。那麼爲什麼我會收到這個錯誤呢?

我也嘗試更新import語句from base.util.logging_utility import method使我有以下錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: No module named 'base' 

任何想法,爲什麼發生這種情況,我該如何糾正呢?

謝謝!

UPDATE

感謝BillyMoinuddin Quadri其建議解決這個問題。由於某些原因,我仍然需要添加__init__.py文件。儘管python 3.3+支持隱式導入,但看起來仍然是需要的。這解決了這個問題。

+0

如何安裝Python的了?通過Python桌面安裝程序或Anaconda? –

+2

把一個空的'__init__。py'文件放在你的'util','project'和'app'目錄中,使它們成爲Python包。 – Billy

+0

@ÉbeIsaac它使用Homebrew安裝。 – Marto

回答

2

您可能沒有打包到PYTHONPATH的路徑。爲了補充一點,這樣做:

import sys 
sys.path.append('/absolute/path/to/base') 

由於在Python 3.3,你不需要__init__.py

對於舊版本,其他可能的原因缺失__init__.py。如果目錄中沒有__init__.py文件,則無法導入該目錄的文件。

正如在Packages Document提到:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

+1

我以爲'__init __。py'是python 3.3+中的[不再需要](http://stackoverflow.com/a/37140173/4942372)。 – Marto

+0

是的,你是對的。我不知道這一點。謝謝你告訴我這件事。其他可能的原因是缺少'sys.path'中的條目。嘗試將其追加到路徑中。 –

+0

你是對的。出於某種原因,我仍然需要添加'__init __。py'文件。這解決了這個問題。 – Marto