ModuleNotFoundError:没有名为“apt_pkg”的模块

ModuleNotFoundError:没有名为“apt_pkg”的模块

如果我在终端中运行不存在的命令(例如lasdfesevlsefoserlks),我会得到下面的输出。为什么?如何恢复正常行为?我可以补充一点,这是在更新到 python3.8 后发生的,我使用的是 ubuntu 18.04。

Traceback (most recent call last):
  File "/usr/lib/command-not-found", line 28, in <module>
    from CommandNotFound import CommandNotFound
  File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 19, in <module>
    from CommandNotFound.db.db import SqliteDatabase
  File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, 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 24, 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/lib/command-not-found", line 28, in <module>
    from CommandNotFound import CommandNotFound
  File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 19, in <module>
    from CommandNotFound.db.db import SqliteDatabase
  File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

答案1

我也遇到了同样的问题。我解决了。

有一个名为 的 Pythoncommand-not-found脚本/usr/lib/command-not-found

升级 Python 版本后,此脚本会更新。至少我的情况是这样的。我从 Python3.6 升级到了 Python3.8。

现在的问题是,这个脚本是基于 Python 的旧版本运行的。所以我进入这个文件,将第一行从

#!/usr/bin/python3(指的是python3.8)

到:

#!/usr/bin/python3.6(这是 Ubuntu 18.04 自带的 Python 版本)

答案2

我在使用“ubuntu-drivers devices”命令时遇到了同样的错误。受到@flowfelis 答案的启发,我更新了 python 版本并解决了该问题。

$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/bin/python3).

  Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python3.7   2         auto mode
* 1            /usr/bin/python3.7   2         manual mode
  2            /usr/bin/python3.8   1         manual mode

Press <enter> to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/bin/python3.8 to provide /usr/bin/python3 (python3) in manual mode

相关内容