terminal引入上层目录的模块,ModuleNotFoundError

本文详细介绍了当Python环境中无法找到特定包时的四种解决方案:通过sys.path.append()动态添加路径,将包路径添加到PYTHONPATH环境变量,将模块安装到site-packages中,以及使用.pth文件。同时提及了虚拟环境的使用,为保持应用依赖项整洁提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

出现这个问题的根本原因是在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回答

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值