查看并添加python中库的搜索路径
根据前文 pip install --user 使用方法和注意事项——python中安装module库到用户packages路径中
我们知道python中除了自身的全局module lib路径以外还是存在用户module lib路径的,为了了解python中库的搜索路径我们需要知道python模块site.py 中的一些变量及使用方法。
site.
getsitepackages
() 获得python中全局site-package路径。
site.
getusersitepackages
() 获得python中用户的site-package路径。
其中,site-package 为python中为第三方module lib安装提供的路径。
在使用 pip install xxx 时,是吧module lib安装到了全局的site-packages路径下的,在使用 pip install xxx --user 时是吧module lib安装到了用户的site-packages下面的。
这里举例:
windows平台下,python3.8版本,查看全局和用户 site-packages路径:
>>> import site
>>> site.getusersitepackages()
'C:\\Users\\81283\\AppData\\Roaming\\Python\\Python38\\site-packages'
>>> site.getsitepackages()
['C:\\Users\\81283\\anaconda3', 'C:\\Users\\81283\\anaconda3\\lib\\site-packages']
其中, site.USER_BASE 可以查看用户module lib的根目录。 site.USER_SITE可以查看用户 module lib的site-packages路径。
-----------------------------------------------------------------
更加全面的查看python中module lib的搜索路径:
python -m site
其中, sys.path 中是所有module lib的搜索路径,
USER_BASE, USER_SITE 已经上面介绍了。
ENABLE_USER_SITE: 用来表示是否启用用户下的module lib搜索路径,也就是当 ENABLE_USER_SITE=True 时,并且C:\\Users\\81283\\AppData\\Roaming\\Python\\Python38\\site-packages 路径存在,此时sys.path中是有用户module lib搜索路径:C:\\Users\\81283\\AppData\\Roaming\\Python\\Python38\\site-packages的。
如果ENABLE_USER_SITE=False 或者 用户module lib搜索路径不存在,此时sys.path中是不出现 C:\\Users\\81283\\AppData\\Roaming\\Python\\Python38\\site-packages的。
演示: 移除用户的 module lib搜索路径:
再次使用 python -m site 查看python所有的module lib搜索路径:
发现 sys.path中已经看不到用户module lib的搜索路径。
===============================================
如何为当前python环境添加新的module lib搜索路径呢???
在当前 sys.path 的所有可搜索路径下面添加 .pth 文件, .pth文件的文件名任意,这个主要看后缀名。在 .pth 文件中添加想要添加的新的 module lib搜索路径。
当前的 搜索路径:
在 sys.path 的任一路径下面创建 .pth 文件,如:
mypath.pth 文件内容:
再次查看 python 的 module lib搜索路径:
可以看到 .pth 文件中写的新的module lib路径已经添加到 sys.path 中。
=====================================================
相关文章
- Python基础(9)--正则表达式
- 编写Python脚本把sqlAlchemy对象转换成dict的教程
- python: easyocr的安装和使用(easyocr 1.6.2 / Python 3.7.15 )
- 【Python】python对象与json相互转换
- 在Python中用PIL做验证码
- Python: 爬虫入门-python爬虫入门教程(非常详细)
- Python语言学习:利用python语言实现调用内部命令(python调用Shell脚本)—命令提示符cmd的几种方法
- Python编程语言学习:包导入和模块搜索路径(包路径)简介、使用方法(python系统环境路径的查询与添加)之详细攻略
- Python:更改默认启动的python程序及其对应的安装包路径(更改pip的默认安装包的路径)图文教程之详细攻略
- Python语言学习:解决python版本升级问题集合(python2系列→Python3系列)导致错误的总结集合
- 〖Python 数据库开发实战 - Python与MySQL交互篇⑤〗- MySQL Connector 模块的删除数据
- 高清无码的MP4如何采集?python带你保存~
- 如何在Python中操作MySQL?
- 这是最强 Python 可视化库,没有之一!
- python快速读取非常大的文件
- Python编程:查看python环境支持的whl
- python 将一个JSON 字典转换为一个Python 对象
- Python:re.sub()实现字符串替换
- 雅虎财经数据python 网络爬虫stock股票 用 Python 通过雅虎财经获取股票数据
- Python 如何使用 HttpRunner 做接口自动化测试 | 干货
- python基础===Python 代码优化常见技巧
- 【Python】3.python实现图片上传到阿里云OSS