????????在使用 Python 安裝包工具 pip 時,經常會遇到下載速度慢的問題。這通常是因為默認使用的官方源 https://pypi.org/simple
在國內訪問速度較慢。為了提高下載速度,我們可以將 pip 源更改為國內的鏡像源。本文將介紹如何臨時和永久地更改 pip 源為國內源。
臨時換源
臨時換源方法是在 pip 安裝包時加上 -i
參數,并指定鏡像源的 URL。
清華源
pip install package_name -i https://pypi.tuna.tsinghua.edu.cn/simple
阿里源
pip install package_name -i https://mirrors.aliyun.com/pypi/simple/
騰訊源
pip install package_name -i http://mirrors.cloud.tencent.com/pypi/simple
豆瓣源
pip install package_name -i http://pypi.douban.com/simple/
永久換源
永久換源方法是修改 pip 的配置文件,使所有包的下載都從指定的鏡像源進行。
修改配置文件
Linux 和 macOS
在根目錄下創建或修改 ~/.pip/pip.conf
文件,添加以下內容:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
其他源的配置:
-
阿里源:
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/[install]
trusted-host = mirrors.aliyun.com
-
騰訊源:
[global]
index-url = http://mirrors.cloud.tencent.com/pypi/simple[install]
trusted-host = mirrors.cloud.tencent.com
-
豆瓣源:
[global]
index-url = http://pypi.douban.com/simple/[install]
trusted-host = pypi.douban.com
Windows
在 %HOMEPATH%\pip\pip.ini
中添加或修改以下內容:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
其他源的配置與 Linux 類似,只需將 pip.conf
文件路徑替換為 pip.ini
。
恢復默認源
如果需要恢復 pip 的默認源,可以使用以下命令:
pip config unset global.index-url
常見問題
安裝包時出現“不受信任的主機”警告
在安裝包時,如果出現類似以下的警告信息:
The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS it is recommended to use HTTPS instead, otherwise you may silence this warning and allow it anyways with ‘--trusted-host mirrors.aliyun.com’.
這是因為 pip 認為該源不受信任。可以使用 --trusted-host
參數臨時解決:
pip install package_name --trusted-host mirrors.aliyun.com
永久信任指定源
在配置文件中添加信任源的設置,以一勞永逸:
[install]
trusted-host = mirrors.aliyun.com
結語
通過以上方法,我們可以有效地提高 pip 包的下載速度,從而提升開發效率。希望本文對大家有所幫助!
如果您有任何問題或建議,歡迎在評論區留言討論。