1. 程式人生 > 其它 >Python 修改 pip 源為國內源

Python 修改 pip 源為國內源

1.臨時換源:

 #清華源
pip install markdown -i https://pypi.tuna.tsinghua.edu.cn/simple
# 阿里源
pip install markdown -i https://mirrors.aliyun.com/pypi/simple/
# 騰訊源
pip install markdown -i http://mirrors.cloud.tencent.com/pypi/simple
# 豆瓣源
pip install markdown -i http://pypi.douban.com/simple/

2.永久換源:

# 清華源
pip config set global
.index-url https://pypi.tuna.tsinghua.edu.cn/simple # 阿里源 pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ # 騰訊源 pip config set global.index-url http://mirrors.cloud.tencent.com/pypi/simple # 豆瓣源 pip config set global.index-url http://pypi.douban.com/simple/
# 換回預設源
pip config unset global.index-url

pip換源的方式

在使用Python安裝包工具pip時經常會出現下載很慢的情況,這其中有很大一部分原因和pip的源有關,在我們安裝python後,通常python直譯器自帶pip這個工具,但是這裡pip是設定的預設源,也就是官方源:

https://pypi.org/simple,這個源在國內的下載速度是很慢的(精通FQ的大神另說),所以我們為了提高包的下載速度我們可以通過換源來實現。

PYPI國內源路徑

換源方式

這裡我們提供兩種換源的方式:

  1. 臨時換源
  2. 永久換源

臨時換源

臨時換源只需要在pip安裝包時,加上一個-i引數後接源的url即可:

# 下載python中的Django包,這裡使用的是豆瓣源
pip install django -i http://pypi.douban.com/simple 

顯然不是一個一勞永逸的方法,只有下少量包的時候有使用的場景,下面我要介紹永久換源的方法,通過這個方式換源,那麼以後我們下載的包就可以全部從這個url中下載了,這樣大大減輕了我們的工作量,明顯比臨時換源的方法更好。

永久換源(更換預設源)

Linux
  1. 在根目錄下建立/修改~/.pip/pip.confpip配置檔案;

  2. 進入檔案新增/修改內容;

    [global]
    index-url=http://pypi.douban.com/simple
    [install]
    trusted-host=pypi.douban.com
    
  3. 儲存檔案並退出;

Windows
  1. windows在%HOMEPATH%\pip\pip.ini中修改上面第二步的內容;(例如:C:\Users\hp\AppData\Roaming\pip\pip.ini)
  2. 儲存檔案退出;

常見問題

  • 安裝包的時候出現

    Collecting beautifulsoup4
    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’.
    Could not find a version that satisfies the requirement beautifulsoup4 (from versions: )
    No matching distribution found for beautifulsoup4
    

    這是一個問題是在pip映象升級報警,只需要新增信任源即可:

    • 臨時換源處理

      pip install beautifulsoup4 --trusted-host mirrors.aliyun.com
      
    • 更換預設源配置(一勞永逸)

      [install]
      trusted-host=pypi.douban.com