[英]Importing a Python module works from command line, but not from PyCharm
我的默認 Python 二進制文件設置為 Python 的 Anaconda 發行版。 這是在/home/karnivaurus/anaconda/bin/python
,我通過將以下內容添加到我的.bashrc
文件中將其設為默認值: export PATH=/home/karnivaurus/anaconda/bin:$PATH
。
我還有一個名為caffe
的 Python 包,它位於/home/karnivaurus/caffe/distribute/python
,我通過將以下內容添加到我的.bashrc
文件中將其添加到包搜索路徑中: export PYTHONPATH=${PYTHONPATH}:/home/karnivaurus/caffe/distribute/python
。
現在,我有一個名為test.py
的簡單 Python 文件,其中包含以下內容:
import caffe
print "Done."
如果我通過在終端中輸入python test.py
來運行它,它運行良好,打印出“完成。”。 我遇到的問題是當我在 PyCharm IDE 中運行它時。 在 PyCharm 中,我將解釋器設置為/home/karnivaurus/anaconda/bin/python
。 但是當我在 PyCharm 中打開test.py
並在 IDE 中運行該文件時,出現以下錯誤:
ImportError: No module named caffe
所以我的問題是:為什么PyCharm在運行Python腳本的時候找不到caffe
模塊,而我從終端運行腳本的時候卻可以找到?
謝謝!
有幾件事可能會導致這種情況。 要調試,請像這樣修改您的test.py
:
# Is it the same python interpreter?
import sys
print(sys.executable)
# Is it the same working directory?
import os
print(os.getcwd())
# Are there any discrepancies in sys.path?
# this is the list python searches, sequentially, for import locations
# some environment variables can fcuk with this list
print(sys.path)
import caffe
print "Done."
在這兩種情況下重試以查找運行時環境中的差異。
編輯:由 PYTHONPATH 環境變量引起的sys.path
存在差異。 這是通過 .bashrc 文件在 shell 中設置的,但未在 PyCharm 的運行時環境配置中設置。
對於附加選項,您可以通過終端使用 pycharm。 並事先導出相應的環境路徑。 這對我有用。 而且我認為這比對代碼進行一些更改要好。 您需要在調試后通過終端運行代碼。
例如,在終端類型中:
$ export LD_LIBRARY_PATH=~/build_master_release/lib:/usr/local/cudnn/v5/lib64:~/anaconda2/lib:$LD_LIBRARY_PATH
$ export PYTHONPATH=~/build_master_release/python:$PYTHONPATH
然后通過charm運行pycharm(pycharm可以通過charm bash軟鏈接):
$ charm
好吧,這可能是一個多余的答案,但是我認為明確指出導致此錯誤的原因很重要。 它發生在我身上很多次,我通過確保將 IDE(pycharm 或 vscode 或任何其他)設置為代碼所在的相同工作目錄來修復它。
例如:我在mlproject/src
目錄中有兩個文件train.py
和config.py
。 我正在嘗試在train.py
運行import config
**在/mlproject/
目錄中運行時,嘗試導入配置時出現錯誤 **
(ml) dude@vscode101:~/mlproject$ python
Python 3.7.6 (default, Jan 8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import config
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'config'
>>>
在 /mlproject/src/` 目錄中運行時,我能夠成功導入配置
(ml) dude@vscode101:~/mlproject/src$ python
Python 3.7.6 (default, Jan 8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import config
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.