商城首页欢迎来到中国正版软件门户

您的位置:首页 >centos查看python版本_CentOS系统python默认版本由python2改为python3

centos查看python版本_CentOS系统python默认版本由python2改为python3

  发布于2026-05-03 阅读(0)

扫一扫,手机访问

一、了解现状:CentOS中的Python环境

在CentOS系统中,如果已经安装了yum,那么系统中通常已经存在某个版本的Python 2。在命令行中直接输入python命令,你大概率会看到Python 2的环境被唤醒:

[root@instance-hrnebyqu src]# python
Python 2.7.5 (default, Apr 11 2018, 07:36:10)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

我们的目标很明确:将python这个shell命令指向Python 3的版本。实现路径通常分为两步:先安装Python 3,然后将python命令链接到新安装的Python 3上。

配置环境与别名

假设Python 3的安装路径已经添加到了~/.bash_profile文件的PATH环境变量中,那么通常不需要再额外修改环境变量。如果尚未添加,则需要执行以下操作:

vim ~/.bash_profile

将Python 3的可执行文件路径(例如/usr/local/python3/bin)添加到PATH中,然后重新加载这个配置文件:

source ~/.bash_profile

接下来,修改~/.bashrc文件来设置命令别名(alias),这是关键的一步:

vim ~/.bashrc

在文件中添加类似下面的几行,明确指定python2python3的路径,并将python命令指向python3

alias python2=/usr/bin/python
alias python3=/usr/local/python3/bin/python3
alias python=/usr/local/python3/bin/python3

这样一来,在命令行中再次输入python,启动的就是Python 3的环境了:

[root@instance-hrnebyqu src]# python
Python 3.6.6 (default, Jul  4 2019, 12:00:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

一个至关重要的注意事项

这里必须划重点:在CentOS系统中,用于软件包管理的yum命令,其底层是依赖Python作为解释器的,并且默认使用的是Python 2。如果粗暴地将全局python命令切换到Python 3,很可能会因为Python 2与Python 3之间的语法兼容性问题,导致yum命令无法正常工作。这是操作前必须警惕的风险点。

如何排查与修复yum问题

yum的主程序文件位于:

/usr/bin/yum

我们可以查看一下这个文件的内容:

#!/usr/bin/python

import sys
try:
    import yum
except ImportError:
    print >> sys.stderr, """\
There was a problem importing one of the Python modules
required to run yum. The error leading to this problem was:

%s

Please install a package which provides this module, or
verify that the module is installed correctly.

It's possible that the above module doesn't match the
current version of Python, which is:

%s

If you cannot solve this problem yourself, please go to
the yum faq at:
http://yum.baseurl.org/wiki/Faq""" % (sys.exc_value, sys.version)
    sys.exit(1)

sys.path.insert(0, '/usr/share/yum-cli')
try:
    import yummain
    yummain.user_main(sys.argv[1:], exit_code=True)
except KeyboardInterrupt, e:

注意看文件的第一行:#!/usr/bin/python。这行“shebang”指明了执行此脚本的解释器路径。如果因为修改了全局python的指向而导致yum报错,最直接的修复方法就是将这一行修改为系统中Python 2解释器的具体路径,例如#!/usr/bin/python2.7。这样就能确保yum继续在Python 2环境下稳定运行,而不受全局别名设置的影响。

本文转载于:https://blog.csdn.net/weixin_39996035/article/details/110884154 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注