ubuntu 下安装最新版 Python (如Python 3.8、 3.9),以及提示No module named “apt_pkg”的解决

正常情况下,直接在ubuntu下执行如下操作,是找不到Python的新版本的:

sudo apt update
sudo apt search python3.9

原因是ubuntu中没有内置Python的源,所以需要添加源。

安装最新版Python,操作如下:

sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.9
python3.9 --version

但是有些ubuntu环境,在执行sudo add-apt-repository ppa:deadsnakes/ppa的时候,可能会出现类似如下错误:

Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 12, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 12, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in <module>
    import apt_pkg

ModuleNotFoundError: No module named 'apt_pkg'

解决方式:

sudo apt install python3-apt
cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.cpython-36m-x86_64-linux-gnu.so

也就是复用Python3.5apt_pkg。当然,不同环境下,/usr/lib/python3/dist-packages下的不一定是Python3.5的版本,需要灵活变通。

参考

https://linuxize.com/post/how-to-install-python-3-9-on-ubuntu-20-04/
https://www.jianshu.com/p/c66f659550f9

Written By

truthhun

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注