掘金 后端 ( ) • 2024-04-26 14:07

pip 是 Python 的包管理工具,用于安装和管理 Python 包。如果你想使用清华大学提供的 Python 包镜像源,可以通过修改 pip 的配置文件或者在使用 pip 命令时指定镜像源。以下是两种常用方法:

方法1:修改配置文件(推荐)

对于不同操作系统,pip 的配置文件位置可能不同:

  • 对于 Unix 和 macOS 系统,配置文件通常位于你的主目录下的 .pip/pip.conf(或者 .config/pip/pip.conf)。
  • 对于 Windows 系统,配置文件通常位于 C:\Users\<Username>\pip\pip.ini

如果这些目录下没有相应的文件,你可以手动创建它们。

这里是配置文件的内容,使用清华大学的镜像源:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn

在 Unix 和 macOS 上,你可以通过以下命令来创建配置文件并写入上述内容:

mkdir -p ~/.pip && echo "[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn" > ~/.pip/pip.conf

在 Windows 上,你可以手动创建或修改 pip.ini 文件,将上述内容粘贴进去。

方法2:命令行参数

你也可以在使用 pip 命令时通过 --index-url 参数指定使用清华源,例如:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

这种方法不需要修改配置文件,但你需要在每次使用 pip 命令时都指定镜像源。

永久性修改

如果你想要永久修改 pip 的默认源,应该使用方法1,即修改配置文件。这样,你在使用 pip 安装包时就不需要每次都指定镜像源了。

请注意,由于网络环境的变化,镜像源的URL有可能会发生变化。如果你发现无法访问,请检查清华大学镜像站的官方网站以获取最新的URL。

其他源

注意啦,除了在公有云上不然这里不推荐其他源

在 Python 社区中,除了清华大学的镜像源之外,还有其他一些著名的镜像源可供选择。以下是一些流行的 Python 包镜像源:

  1. 阿里云 (Alibaba Cloud)

    [global]
    index-url = https://mirrors.aliyun.com/pypi/simple/
    [install]
    trusted-host = mirrors.aliyun.com
    
  2. 中国科技大学 (University of Science and Technology of China, USTC)

    [global]
    index-url = https://pypi.mirrors.ustc.edu.cn/simple/
    [install]
    trusted-host = pypi.mirrors.ustc.edu.cn
    
  3. 豆瓣(Douban)

    [global]
    index-url = https://pypi.doubanio.com/simple/
    [install]
    trusted-host = pypi.doubanio.com
    
  4. 华为云 (Huawei Cloud)

    [global]
    index-url = https://mirrors.huaweicloud.com/repository/pypi/simple
    [install]
    trusted-host = mirrors.huaweicloud.com
    
  5. 腾讯云 (Tencent Cloud)

    [global]
    index-url = https://mirrors.cloud.tencent.com/pypi/simple
    [install]
    trusted-host = mirrors.cloud.tencent.com
    

要使用这些源,你可以按照之前提到的方法修改 pip 配置文件,或者在命令行中使用 --index-url 参数。例如,如果你想使用阿里云的镜像源,可以在命令行中输入:

pip install -i https://mirrors.aliyun.com/pypi/simple/ some-package

或者将阿里云的镜像源设置到你的 pip 配置文件中,这样以后所有的 pip 命令都会默认使用这个源。

请注意,镜像站点可能会不定期更改其服务的URL,如果你发现某个镜像源无法使用,请访问对应的官方网站以获取最新的URL信息。