关于Ubuntu有多个Python版本的解决方案

659 阅读1分钟

执行:which 软件名,会输出软件路径:可以看我我这有好几个python版本。

yu@librity:~$ which python
/usr/bin/python
yu@librity:~$ which python3
/usr/bin/python3
yu@librity:~$ which python2
/usr/bin/python2
yu@librity:~$ 

现在看下这些文件的具体信息:
cd /usr/bin
ls -l | grep python

yu@librity:~$ cd /usr/bin
yu@librity:/usr/bin$ ls -l | grep python
lrwxrwxrwx 1 root root          24  9月 14 17:54 python -> /etc/alternatives/python
lrwxrwxrwx 1 root root           9  7月 28  2021 python2 -> python2.7
lrwxrwxrwx 1 root root          10  3月 25 20:41 python3 -> python3.10
yu@librity:/usr/bin$ 

-> 这个标记的意思就是软连接的意思。可以看到上面的都设置了软连接,python指向了/etc/alternatives/python文件。
注意:我在这里曾经栽了很大的跟头,我在执行python的时候报错:

yu@librity:python
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = (not set)
  program name = 'python'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = '/usr/bin/python'
  sys.base_prefix = '/usr'
  sys.base_exec_prefix = '/usr'
  sys.executable = '/usr/bin/python'
  sys.prefix = '/usr'
  sys.exec_prefix = '/usr'
  sys.path = [
    '/usr/lib/python38.zip',
    '/usr/lib/python3.8',
    '/usr/lib/lib-dynload',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007fc19c386740 (most recent call first):
<no Python frame>

报了一堆什么 Could not find 的问题。然后我又无意间执行了这个代码
update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1

yu@librity:~$ update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
Can not upgrade
Your python install is corrupted. Please fix the '/usr/bin/python' symlink.

明确告诉我我的python软连接损坏了。然后我执行ls -l | grep python 后发现python没有指向任何文件,果然损坏了。 所以解决办法就是我给他添加一个软连接:

sudo ln -sf /usr/bin/python2.7 /usr/bin/python

所有的问题都解决了,现在就可以手动切换我们的python版本了:

  1. 执行:查看所有的可以替代的版本,你没配置过肯定没任何输出。
update-alternatives --list python 
  1. 添加替代信息
update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1  
update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2 
  1. 在查看下:
yu@librity:/usr/bin$ update-alternatives --list python 
/usr/bin/python2.7
/usr/bin/python3
/usr/bin/python3.10
yu@librity:/usr/bin$ 
  1. 随意替换顺序
root@librity:/home/yu# update-alternatives --config python 
有 3 个候选项可用于替换 python (提供 /usr/bin/python)。

  选择       路径               优先级  状态
------------------------------------------------------------
* 0            /usr/bin/python3.10   2         自动模式
  1            /usr/bin/python2.7    1         手动模式
  2            /usr/bin/python3      2         手动模式
  3            /usr/bin/python3.10   2         手动模式

要维持当前值[*]请按<回车键>,或者键入选择的编号:0

输入你要最有优先的序号,比如这里我输入0。那么我在控制台输入python得到的版本将是python3.10的。


全部完成! 博客