Ubuntu 22.04 修改默认 Python 版本为 Python3 笔记

Ubuntu 系统默认使用的是 Python 2.x 作为 python 命令的映射,而现代开发(如 pip、Django、Flask、Scrapy 等)大多基于 Python 3。本笔记将教你如何将默认 python 命令指向 Python3(如 Python 3.8、3.10)。

背景说明

在 Ubuntu 22.04 中:

  • 系统默认安装了 Python 2 和 Python 3;
  • 运行 python 命令默认启动的是 Python 2;
  • 运行 python3 启动的是 Python 3.x(通常是 3.10);

某些新脚本或依赖使用 python 命令,会触发 Python 2,导致语法错误或运行失败。


步骤 1:确认当前 python 绑定

bash 复制代码
which python
python --version

如果输出:

bash 复制代码
/usr/bin/python
Python 2.7.18

说明系统默认绑定的是 Python2。


步骤 2:使用 update-alternatives 正确切换至 Python3

bash 复制代码
# 添加 Python3.x(比如 python3.10)为 python 的候选项
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 100

# 配置默认版本
sudo update-alternatives --config python

如果有多个版本,系统会让你选择要用哪一个作为默认。

例如:

复制代码
There are 2 choices for the alternative python (providing /usr/bin/python):

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python2     50        auto mode
  1            /usr/bin/python2     50        manual mode
  2            /usr/bin/python3     100       manual mode

Press <enter> to keep the current choice[*], or type selection number: 2

输入 2 并回车。


步骤 3:验证是否生效

bash 复制代码
python --version
which python

输出应为:

复制代码
Python 3.10.12
/usr/bin/python

步骤 4(可选):pip 同样做软连接

bash 复制代码
sudo ln -sf /usr/bin/pip3 /usr/bin/pip
pip --version

如需恢复为 Python2:

bash 复制代码
sudo update-alternatives --config python
# 选择 /usr/bin/python2

或者删除:

bash 复制代码
sudo update-alternatives --remove python /usr/bin/python3

注意事项

  • 不建议删除系统自带的 python2,某些老工具仍依赖它;
  • 使用 update-alternatives 更安全,避免破坏系统依赖;
  • update-alternatives 修改的是 /usr/bin/python 的指向(通过自动管理的软链接);

建议

在项目开发中仍建议使用虚拟环境:

bash 复制代码
python -m venv venv
source venv/bin/activate

参考

相关推荐
辰海Coding41 分钟前
MiniSpring框架学习笔记-解决循环依赖的简化IoC容器
笔记·学习
曲幽42 分钟前
我用了FastApiAdmin后,连夜把踩过的坑都整理出来了
redis·python·postgresql·vue3·fastapi·web·sqlalchemy·admin·fastapiadmin
晓梦林1 小时前
cp520靶场学习笔记
android·笔记·学习
小鹏linux1 小时前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
心中有国也有家2 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
前端若水2 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
玄米乌龙茶1232 小时前
LLM成长笔记(三):API 开发基础
笔记
Upsy-Daisy2 小时前
AI Agent 项目学习笔记(八):Tool Calling 工具调用机制总览
人工智能·笔记·学习
涛声依旧-底层原理研究所3 小时前
残差连接与层归一化通俗易懂的详解
人工智能·python·神经网络·transformer
csdn_aspnet3 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展