1. PIP配置文件层级
根据官方文档: https://pip.pypa.io/en/stable/topics/configuration/ 的解释,PIP的配置有三个“层级”,分别对应着三个配置文件,且在Linux/Windows下都存放于不同的位置。这三个层级分别是:
- Global: 系统级
- User: 用户级
- Site: (虚拟)环境级
以下是三个层级的文件在Linux/Windows下分别的存放位置
| Linux | Windows |
系统级 |
|
|
用户级 |
|
|
虚拟环境级 |
|
|
2. PIP配置文件生效顺序
在同时配置了多级PIP环境后,配置文件的生效顺序会按以下顺序逐级加载,后面加载的值会覆盖前面的:
PIP_CONFIG_FILE => Global => User => Site
其中PIP_CONFIG_FILE是一个环境变量。这种多级配置的覆盖顺序比较符合人们的常识,即:越具体,越偏局部的配置会覆盖掉越通用,越全局的配置。
3. 使用命令行配置各级文件
pip3 config提供--global
, --user
, --site
三个参数来分别对于三个层级的配置,使用命令行配置pip.conf文件的一大好处在于:你无需记忆不同层级的文件位置。
我们以配置镜像源为例,演示一下使用命令行配置PIP
3.1 配置全局镜像源
# 检查当前配置
pip3 config --global list
# 重新配置
pip3 config --global set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip3 config --global set install.trusted-host mirrors.aliyun.com
# 再次检查当前配置
pip3 config --global list
使用命令行配置全局镜像源时,可能会有这样一个问题:如果运行命令的当前用户不是root,是没有权限创建或修改/etc/pip.conf文件的,于是就会得到一个报错:
PermissionError: [Errno 13] Permission denied: '/etc/pip.conf'
但是如果前面添加sudo,切换为root用户执行,则root用户环境(即/usr/local)未必安装了PIP,此时往往会报这个错误:
sudo: pip: command not found
此时则需要先在root环境(即/usr/local)下安装PIP。如果不想这样复杂,可以参考后面直接修改pip.conf文件的作法。
3.2 配置局部镜像源
# 检查当前配置
pip3 config --user list
# 重新配置
pip3 config --user set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip3 config --user set install.trusted-host mirrors.aliyun.com
# 再次检查当前配置
pip3 config --global list
3.3 配置虚拟环境镜像源
# 创建一个虚拟环境
python3 -m venv ${HOME}/my-venv
# 激活虚拟环境
source ${HOME}/my-venv/bin/activate
# 检查当前配置
pip3 config --site list
# 重新配置
pip3 config --site set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip3 config --site set install.trusted-host mirrors.aliyun.com
# 再次检查当前配置
pip3 config --site list
4. 直接修改各级配置文件
经过上一节的介绍,我们可以看到大多数情况下使用命令行配置PIP是最好的选择。只有在一些特殊情况下,我们需要跳过命令行,手动修改配置文件。在3.1节就举出过一个例子:当前用户没有权限修改/etc/pip.conf
,而改用sudo后,可能找不到pip, 要在root环境(即/usr/local下)重新安装PIP,此时可以直接修改/etc/pip.conf
,以下给出参考脚本,修改其他层级的配置文件同理,记得改为正确的目标文件即可:
# 检查当前配置
pip3 config --global list
# 重新配置
sudo tee /etc/pip.conf <<EOF
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host = mirrors.aliyun.com
EOF
# 再次检查当前配置
pip3 config --global list
参考:
https://www.lfhacks.com/tech/python-pip-config/
https://pip.pypa.io/en/stable/topics/configuration/
https://pip.pypa.io/en/stable/cli/pip_config/