首页/实用指南/基础环境

Python 3 安装教程:Windows、macOS、Linux 与国内 pip 镜像配置

很多命令行工具需要 Python 环境。这里集中说明 Python 3 的安装、pip 检查以及国内网络下的 PyPI 镜像配置,后续其他教程直接引用本页。

1. Windows 安装 Python

打开 Python 官方 Windows 下载页面,按照官方说明安装 Python 3。

安装完成后打开 PowerShell:

powershell
python --version

能够看到 Python 3 的版本号即可。

检查 pip

powershell
python -m pip --version

以后安装 Python 软件包可以使用:

powershell
python -m pip install PACKAGE_NAME

2. macOS 安装 Python

打开 Python 官方 macOS 下载页面,下载并安装 Python 3。

安装完成后打开 Terminal:

bash
python3 --version

检查 pip:

bash
python3 -m pip --version

3. Linux 安装 Python

先检查系统是否已经安装 Python 3:

bash
python3 --version
python3 -m pip --version

Debian / Ubuntu

bash
sudo apt update
sudo apt install python3 python3-pip

安装后再次检查:

bash
python3 --version
python3 -m pip --version

4. 国内 pip 下载慢:使用清华 PyPI 镜像

临时使用镜像安装软件包:

Windows

powershell
python -m pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple PACKAGE_NAME

macOS / Linux

bash
python3 -m pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple PACKAGE_NAME

需要长期使用时,可以设为默认源。

Windows

powershell
python -m pip config set global.index-url https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple

macOS / Linux

bash
python3 -m pip config set global.index-url https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple

查看当前配置:

bash
python3 -m pip config list

5. 使用中科大 PyPI 镜像

清华镜像访问不理想时,也可以使用中科大镜像:

bash
python3 -m pip config set global.index-url https://mirrors.ustc.edu.cn/pypi/simple

Windows 将 python3 换成 python

6. 恢复官方 PyPI

Windows

powershell
python -m pip config unset global.index-url

macOS / Linux

bash
python3 -m pip config unset global.index-url

7. pip 无法使用

如果出现 No module named pip,可以尝试:

Windows

powershell
python -m ensurepip --default-pip

macOS / Linux

bash
python3 -m ensurepip --default-pip

Linux 如果出现 externally-managed-environment,不要直接使用 --break-system-packages 修改系统 Python。