背景:
在云服务器上尝试大模型应用开发时,缺少依赖的包,于是pip install **, 超时了,加上参数–default-timeout=500,也不行。
问题:
pip 默认使用国外源,添加参数(-i https://mirrors.aliyun.com/pypi/simple/)换成国内源就快了。
解决方法:
方法一:临时使用镜像源(推荐)
在执行pip install
命令时,通过-i
参数指定临时使用的镜像源,例如使用阿里云镜像:
pip --default-timeout=500 install -i https://mirrors.aliyun.com/pypi/simple/ XXX(换成要下载的名称)
方法二:配置全局默认镜像源
创建或修改pip的配置文件,设置永久默认镜像源:
Linux/macOS
-
创建配置目录(如果不存在):
mkdir -p ~/.pip
-
编辑配置文件
~/.pip/pip.conf
,添加以下内容(以阿里云镜像为例):[global] index-url = https://mirrors.aliyun.com/pypi/simple/ [install] trusted-host = mirrors.aliyun.com
Windows
-
创建配置目录(如果不存在):
C:\Users\你的用户名\AppData\Roaming\pip\
-
新建文件
pip.ini
,添加以下内容:[global] index-url = https://mirrors.aliyun.com/pypi/simple/ [install] trusted-host = mirrors.aliyun.com
常用国内镜像源地址
- 阿里云: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/
验证配置是否生效
执行以下命令查看当前使用的镜像源:
pip config list
输出应包含类似以下内容:
global.index-url='https://mirrors.aliyun.com/pypi/simple/'
install.trusted-host='mirrors.aliyun.com'
通过上述配置,之后使用pip安装包时将默认从国内镜像源下载,大幅提高下载速度和稳定性。
安装错误:需要卸载包,内容如下:
要卸载指定版本的Python包,可以在pip uninstall
命令中直接指定包名和版本号。以下是具体的操作方法:
命令格式
pip uninstall <包名>==<版本号>
示例
假设你想卸载版本为1.2.3
的numpy
包:
pip uninstall numpy==1.2.3
执行后,pip会确认是否卸载该特定版本:
Found existing installation: numpy 1.2.3
Uninstalling numpy-1.2.3:
Would remove:
/path/to/python/site-packages/numpy-1.2.3.dist-info/*
/path/to/python/site-packages/numpy/*
Proceed (Y/n)?
输入Y
并回车确认卸载。
注意事项
-
版本号格式
版本号需严格匹配已安装的包版本(如1.2.3
、2.0.0rc1
等)。若版本不存在,pip会提示:ERROR: Could not find a version that satisfies the requirement numpy==1.99.99 (from versions: ...)
-
多个版本共存
如果系统中安装了同一个包的多个版本(如numpy 1.20.0
和1.21.0
),指定版本号只会卸载该版本,其他版本不受影响。 -
依赖冲突
卸载特定版本可能导致其他包依赖冲突。例如,若包A
依赖numpy>=1.20.0
,而你卸载了numpy 1.21.0
,可能需要重新安装兼容版本。
验证卸载结果
卸载后,可通过以下命令检查包是否仍存在:
pip show <包名>
若输出WARNING: Package(s) not found: <包名>
,则表示已成功卸载。
批量卸载指定版本
如果需要批量卸载多个包的特定版本,可以编写简单的Shell脚本(Linux/macOS):
# uninstall_packages.sh
#!/bin/bash
packages=(
"numpy==1.2.3"
"pandas==1.4.2"
"matplotlib==3.5.1"
)
for pkg in "${packages[@]}"; do
pip uninstall -y "$pkg"
done
保存为uninstall_packages.sh
,添加执行权限后运行:
chmod +x uninstall_packages.sh
./uninstall_packages.sh
通过以上方法,你可以精确控制要卸载的包版本,避免误操作。