terminal引入上層目錄的模塊,ModuleNotFoundError

出現這個問題的根本原因是在PYTHONPATH中找不到,你需要做的是告訴python去哪裏找這個包

option1:
在文件裏引入這個module之前,通過sys.path.append()加入sys,path中,這個路徑應該是整個包的路徑(到上級目錄爲止)

import sys
sys.append(os.path.dirname(os.path.dirname(...os.path.abspath(__file__))))

可以通過ipython不斷測試找到正確路徑

option2:
將包路徑加入PYTHONPATH中

export PYTHONPATH=/Users/xxx/Documents/yyy/insurance/KGBuild/ML

echo $PYTHONPATH發現已經存在這個目錄

option3:
打開ipython

import sys
sys.path

然後會看到在sys.path中的路徑,其中有個site-packages,這是安裝python第三方包的時候存放的路徑,所以我們也可以像安裝第三方包一樣將這個模塊安裝到site-package中。但是這個要自己寫一個 setup.py ,目前我還不會寫。

option4:
Python looks at the PYTHONPATH variable to setup its sys.path list on startup. But it also looks for special .pth files in the Python site-packages folder. (If you don’t know where the site-packages folder is, then that’s probably another StackOverflow question.)

The simplest .pth file contains a single line with a file path:

/path/containing/the/module/you/want/to/import

Python will pick that up and add it to the sys.path list.

Option 4:(還沒實踐過,不會,歡迎留言)
Use a virtual environment.
This isn’t directly a solution to your immediate problem, but I mention it for completeness. Python virtual environments allow you to contain all the dependencies for your application in a self-contained isolation chamber. All of the above (Options 1 through 3) still apply within a virtual environment, but sometimes a virtual environment helps to keep things tidy…and understandable.

If you can use virtualenvwrapper, it makes virtual environment management a breeze. Otherwise, you can use the low-level virtualenv (Python 2) and pyenv (Python 3) without much pain.

stackoverflow回答

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章