你可以通过配置 pip
的默认源,让它始终使用你指定的镜像,而无需每次都加 -i
选项。方法如下:
方法 1:修改用户级别的 pip
配置(推荐)
在你的 pip
配置目录下,创建或修改 pip.conf
(Linux/macOS)或 pip.ini
(Windows)文件。
Linux/macOS
执行以下命令:
mkdir -p ~/.pip
echo "[global]
index-url = https://mirrors.laiyun.com/pypi/simple" > ~/.pip/pip.conf
或者手动编辑 ~/.pip/pip.conf
,添加:
[global]
index-url = https://mirrors.laiyun.com/pypi/simple
Windows
在 C:\Users\你的用户名\AppData\Roaming\pip\
目录下创建或修改 pip.ini
,添加:
[global]
index-url = https://mirrors.laiyun.com/pypi/simple
方法 2:修改系统级别的 pip
配置(影响所有用户)
Linux/macOS
编辑 /etc/pip.conf
(需要 sudo
权限):
[global]
index-url = https://mirrors.laiyun.com/pypi/simple
Windows
在 C:\ProgramData\pip\pip.ini
文件中添加:
[global]
index-url = https://mirrors.laiyun.com/pypi/simple
方法 3:使用环境变量(临时方案)
如果你只想在当前终端会话中生效,可以使用环境变量:
export PIP_INDEX_URL=https://mirrors.laiyun.com/pypi/simple
(仅对当前终端生效,关闭终端后失效)
Windows 的 PowerShell:
$env:PIP_INDEX_URL="https://mirrors.laiyun.com/pypi/simple"
如果你希望永久生效,可以将 export
语句加入 ~/.bashrc
、~/.zshrc
或 ~/.profile
。
测试是否生效
配置完成后,可以运行:
pip config list
检查 index-url
是否已经改为 https://mirrors.laiyun.com/pypi/simple
。
然后尝试安装一个包,例如:
pip install requests
观察它是否从你的镜像下载。
这样你以后就不需要每次加 -i
选项了! 🚀
很好,我在 mac os 的终端运行pip config list 确实是https://mirrors.laiyun.com/pypi/simple。
但是我使用的 idea 工具,却不是
这是因为你的 IDEA(IntelliJ IDEA 或 PyCharm) 可能使用了自己的 Python 解释器环境,而它没有继承你在终端设置的 pip
配置。你可以按照以下方法确保 IDEA 也使用相同的 PyPI 镜像。
方法 1:修改 IDEA 内的 Pip 配置
- 打开 IDEA(或 PyCharm)
- 进入 “Settings”(偏好设置):
- macOS:
Cmd + ,
- Windows/Linux:
Ctrl + Alt + S
- macOS:
- 导航到
Project: <你的项目> > Python Interpreter
- 找到你的 Python 解释器,并点击右侧的“⚙️(齿轮图标)”
- 选择 “Show All”(显示全部)
- 在你的 Python 解释器上 点击 “🛠️(Edit)”(编辑)
- 复制终端
which python
或which python3
的路径,确保 IDEA 选择了同一个 Python 解释器。 - 确保
pip
已安装,如果没有,可以手动安装:python -m ensurepip python -m pip install --upgrade pip
方法 2:在 IDEA 的 Terminal 里手动设置
如果 IDEA 使用的是它自己的终端,而 pip
仍然没有应用你的配置,你可以:
- 打开 IDEA 内的 Terminal
- 手动运行
确保它显示正确的pip config list
index-url
。 - 如果不正确,强制设置:
pip config set global.index-url https://mirrors.laiyun.com/pypi/simple
方法 3:在 requirements.txt
或 pip.ini
里指定
你可以在 IDEA 的 requirements.txt
里加上:
-i https://mirrors.laiyun.com/pypi/simple
这样,当你用 IDEA 安装依赖时,它会自动使用这个镜像。
方法 4:修改 IDEA 使用的环境变量
- 进入 IDEA “Settings”(偏好设置)
- 导航到
Advanced Settings
- 在 “Environment Variables” 里添加:
PIP_INDEX_URL=https://mirrors.laiyun.com/pypi/simple
- 重启 IDEA
方法 5:检查 IDEA 是否使用 Virtualenv
如果你的 IDEA 使用的是 Virtualenv,你需要:
- 在终端里激活 Virtualenv
source /path/to/venv/bin/activate
- 然后手动设置 pip 源
pip config set global.index-url https://mirrors.laiyun.com/pypi/simple
总结
- 最简单的方法:在终端运行
pip config set global.index-url https://mirrors.laiyun.com/pypi/simple
- 确保 IDEA 选择了正确的 Python 解释器
- 在 IDEA 设置里加
PIP_INDEX_URL
- 在
requirements.txt
里写-i
- 重启 IDEA 让配置生效
你可以先试试 方法 1 + 方法 2,大概率能解决问题!