本文主要是介绍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回答
这篇关于terminal引入上层目录的模块,ModuleNotFoundError的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!