发布于2026-07-20 阅读(0)
扫一扫,手机访问
在 CentOS 系统里,只要装了 yum,通常都会自带一个 Python 2 的版本。在命令行敲下 python,看到的多半是这样的画面:
[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 这个命令默认指向 Python 3。怎么做?先装好 Python 3,然后把 python 这个软连接或别名指向它就行。
假设你已经把 Python 3 的路径加到了 ~/.bash_profile 的 PATH 里,环境变量这块就不用再动了。如果还没加,需要先执行:
vim ~/.bash_profile
把 Python 3 的路径补上,然后 source ~/.bash_profile 重载一下。
接下来修改 ~/.bashrc 文件:
vim ~/.bashrc
在里边加上三行别名:
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 2 作为解释器。如果你把系统默认的 python 改成 Python 3,由于 2 和 3 的兼容性问题,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。如果因为修改默认 Python 导致 yum 出问题,解决办法很简单:把这个 Shebang 改成 #!/usr/bin/python2.x(具体版本号看你系统里 Python 2 的实际路径),就能恢复。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8