在 python 中切换镜像源主要涉及 pip 包管理器 和 conda 环境(如 anaconda、miniconda) 的配置。国内访问 python 官方源(pypi)可能较慢,因此推荐使用国内镜像源(如阿里云、清华大学、豆瓣等)。以下是具体切换方法:
一、pip 更换镜像源
1. 临时使用镜像源(单次命令)
在 pip install
命令中通过 -i
参数指定镜像源:
pip install 包名 -i https://mirrors.aliyun.com/pypi/simple/ # 阿里云 pip install 包名 -i https://pypi.tuna.tsinghua.edu.cn/simple # 清华大学 pip install 包名 -i https://pypi.doubanio.com/simple/ # 豆瓣
2. 永久配置镜像源
创建或修改 pip
配置文件:
# linux/macos:创建配置目录 mkdir -p ~/.pip # 编辑配置文件(若不存在会自动创建) nano ~/.pip/pip.conf
在配置文件中添加以下内容(以阿里云为例):
[global] index-url = https://mirrors.aliyun.com/pypi/simple/ [install] trusted-host = mirrors.aliyun.com # 信任该镜像源,避免 ssl 警告
保存后,所有 pip install
命令都会默认使用该镜像源。
3. 常用国内镜像源地址
镜像源 | url |
---|---|
阿里云 | https://mirrors.aliyun.com/pypi/simple/ |
清华大学 | https://pypi.tuna.tsinghua.edu.cn/simple |
中国科学技术大学 | https://pypi.mirrors.ustc.edu.cn/simple/ |
豆瓣 | https://pypi.doubanio.com/simple/ |
二、conda 更换镜像源(适用于 anaconda/miniconda)
1. 添加镜像源
# 添加清华镜像 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/ # 添加 conda-forge 社区源(可选,包含更多包) conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/ # 设置搜索时显示通道地址 conda config --set show_channel_urls yes
2. 查看配置结果
conda config --show channels
输出应类似:
channels: - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/ - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/ - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ - defaults
3. 恢复默认源
conda config --remove-key channels
三、验证镜像源是否生效
1. pip 验证
pip install -vvv 包名 2>&1 | grep "fetching" # 查看下载地址是否为镜像源
2. conda 验证
conda install 包名 # 安装时观察下载地址
四、注意事项
- 镜像同步延迟:国内镜像会定期同步 pypi 官方源,但可能存在数小时的延迟。若遇到“找不到包”的问题,可临时切换回官方源。
- 虚拟环境独立配置:若使用虚拟环境(如
venv
、virtualenv
),配置文件路径可能不同(如~/.virtualenvs/环境名/pip.conf
)。 - 优先使用官方源:若安装特定版本的包遇到问题,可尝试使用官方源:
pip install 包名 -i https://pypi.org/simple
到此这篇关于python中切换镜像源的几种实现方法的文章就介绍到这了,更多相关python 切换镜像源内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论