在 Ubuntu 中修改 Python 环境变量:从 Python 2 到 Python
在许多 Linux 发行版中,Python 2 和 Python 3 可能是同时存在的。随着 Python 2 的官方支持已于 2020 年 1 月 1 日结束,大许多人选择将考虑使用 Python 3 作为默认的 Python 解释器。在 Ubuntu 中,你可以通过修改环境变量来实现这一点。本文将为你详细介绍如何将 Ubuntu 环境中的 Python 变量从 Python 2 改为 Python 3,并提供相关代码示例。
理解环境变量
环境变量是操作系统用于管理进程和系统设置的一种机制。它们会影响程序的运行方式。例如,PATH
是一个环境变量,它包含系统查找可执行文件的路径。如果你希望系统默认使用 Python 3 而不是 Python 2,你就需要修改一个特定的环境变量。
检查当前 Python 版本
首先,你可以通过以下命令来检查当前系统中安装的 Python 版本:
python --version
运行该命令后,你将看到类似以下的输出:
Python 2.7.18
如果你安装了 Python 3,系统也可以通过 python3
命令来访问。
修改环境变量
1. 使用 update-alternatives
Ubuntu 提供了一种简便的方式来处理多个版本的程序,那就是使用 update-alternatives
命令。你可以使用它来添加、调整和删除系统中的程序版本。
首先,使用以下命令将 Python 3 添加为系统的 Python 版本之一:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1
接下来,使用以下命令启动交互式选择菜单:
sudo update-alternatives --config python
这会显示已安装的 Python 版本及其优先级,例如:
There are 2 choices for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python2 1 auto mode
1 /usr/bin/python2 1 manual mode
2 /usr/bin/python3 1 manual mode
Press enter to keep the current choice[*], or type selection number:
你可以选择 2
来将默认 Python 版本更改为 Python 3。
2. 确认更改
更改完成后,再次运行 python --version
命令来确认当前的 Python 版本是否已更改为 Python 3:
python --version
应该输出类似如下内容:
Python 3.8.10
修改 .bashrc
文件
有时,你可能还需要在用户级别上设置 Python 的环境变量。这可以通过编辑 .bashrc
文件完成。
打开 .bashrc
文件,使用你喜欢的文本编辑器,例如:
nano ~/.bashrc
然后在文件底部添加以下行:
alias python=python3
保存文件并重新加载 .bashrc
文件:
source ~/.bashrc
这样,无论何时在该用户的 shell 会话中使用 python
命令,系统都会执行 python3
。
测试
现在,你可以创建一个简单的 Python 脚本来测试这一切是否如你所愿。创建一个名为 test.py
的文件:
# test.py
print("Hello, Python!")
然后运行以下命令:
python test.py
如果你看到输出Hello, Python!
,说明你成功地将默认 Python 版本从 Python 2 更改为 Python 3。
总结
在 Ubuntu 中将默认的 Python 版本从 Python 2 修改为 Python 3 是一项相对简单的任务。通过使用 update-alternatives
命令,用户可以轻松选择所需的 Python 版本。而通过修改 .bashrc
文件,用户也可以实现用户级别的环境变量设置。现在,你可以舒服地使用 Python 3 开发应用,而不必担心与已弃用的 Python 2 版本的兼容性问题。
序列图示例
以下是一个序列图,展示了将 Python 版本更改的过程:
sequenceDiagram
participant User
participant Terminal
participant System
User->>Terminal: Run python --version
Terminal->>System: Check current Python version
System-->>Terminal: Python 2.7.18
Terminal-->>User: Output Python version
User->>Terminal: Run sudo update-alternatives --config python
Terminal->>System: Show current alternatives
System-->>Terminal: Show available Python versions
User->>Terminal: Select Python 3
Terminal->>System: Update alternatives
System-->>Terminal: Confirm change
Terminal-->>User: Output confirmed
User->>Terminal: Run python --version
Terminal->>System: Check current Python version
System-->>Terminal: Python 3.8.10
Terminal-->>User: Output Python version
通过以上步骤,你完成了从 Python 2 到 Python 3 的转变。随着这个变化,你将能够使用更现代的特性和更好的库支持,享受更加方便和强大的编程体验。