温馨提示×

ubuntu python如何配置

小樊
44
2026-09-04 13:22:34
栏目: 编程语言

在 Ubuntu 上配置 Python,通常分为系统 Python 管理多版本切换虚拟环境包管理几个部分。下面按常见使用场景给你一套清晰配置方案。


一、检查系统已有 Python

Ubuntu 一般自带 Python 3:

python3 --version
which python3

⚠️ 不要动系统自带的 python3(apt 依赖它)


二、安装指定 Python 版本(如 3.10 / 3.11)

sudo apt update
sudo apt install python3.10 python3.10-venv python3.10-dev

安装开发依赖(编译包用):

sudo apt install build-essential libssl-dev zlib1g-dev

三、使用 update-alternatives 管理多版本

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 2

切换版本:

sudo update-alternatives --config python3

四、推荐使用虚拟环境(非常重要)

1️⃣ 创建虚拟环境

python3 -m venv venv

2️⃣ 激活环境

source venv/bin/activate

3️⃣ 退出环境

deactivate

✅ 每个项目一个 venv,避免污染系统


五、pip 配置

升级 pip:

python -m pip install --upgrade pip

国内加速(可选):

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

六、使用 pyenv(推荐进阶用户)

适合多版本 Python 共存:

curl https://pyenv.run | bash

加入 ~/.bashrc

export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"

使用:

pyenv install 3.11.6
pyenv local 3.11.6

七、常见问题

pip 不存在?

sudo apt install python3-pip

apt 报错 python 被改?

不要用 ln -s 改系统 python 指向


如果你是:

  • ✅ 新手 → 用 venv
  • ✅ 多项目 → 用 pyenv + venv
  • ✅ 服务器 → 固定版本 + 虚拟环境

告诉我你的 Ubuntu 版本 + 使用目的(学习 / 开发 / 服务器),我可以给你更精确配置方案。

0