Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'ModuleNotFoundError: No module named 'apt_pkg'?

I'm running code sudo apt update and fetch error

ModuleNotFoundError: No module named 'apt_pkg'.

Please, help me solve it.

sudo apt update


Hit:20 http://ppa.launchpad.net/xorg-edgers/ppa/ubuntu bionic InRelease       
Fetched 93,3 kB in 2s (42,4 kB/s)                   
Traceback (most recent call last):
  File "/usr/lib/cnf-update-db", line 8, in <module>
    from CommandNotFound.db.creator import DbCreator
  File "/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py", line 11, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
Reading package lists... Done
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/lib/command-not-found/ -a -e /usr/lib/cnf-update-db; then /usr/lib/cnf-update-db > /dev/null; fi'
E: Sub-process returned an error code
like image 998
Mogikan Avatar asked May 20 '19 10:05

Mogikan


People also ask

How to fix no module named apt_ pkg?

Importerror no module named apt_pkg is mainly because of python-apt package. Either python-apt package is not installed or is incompatible. So the fix for this error (no module named apt_pkg) is straight to reinstall/ upgrade the python-apt package.

What is Python apt?

Python APT's library provides access to almost every functionality supported by the underlying apt-pkg and apt-inst libraries. This means that it is possible to rewrite frontend programs like apt-cdrom in Python, and this is relatively easy, as can be seen in e.g. Writing your own apt-cdrom.


3 Answers

In my case the problem was due to upgrading python version from 3.6 to 3.8.

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 2

sudo update-alternatives --config python3

Solved by:

Settings back the python version to 3.6

like image 108
nsola Avatar answered Oct 11 '22 13:10

nsola


Just reinstalled python3-apt and the error disappeared

sudo apt remove python3-apt

restart and then install,

sudo apt install python3-apt

NOTE: Use only if, python3 is a new installation dependency. Else it can screw existing python3 based setups on your system. Use of --reinstall is a safer bet though.

like image 48
Vijay Avatar answered Oct 11 '22 13:10

Vijay


In my case, the problem was that I removed original /usr/bin/python3 symlink on Ubuntu 18.04 and replaced it with one pointing to python3.8. Problem disappeared when I restored the original pointing to python3.6

My takeaway is: if you need custom version of some library or module, install it in an isolated environment, do not mess up with system settings. Otherwise you are at risk of breaking something which can be noticed only later when it's difficult to figure out what exactly is wrong.

like image 18
Fedorov7890 Avatar answered Oct 11 '22 14:10

Fedorov7890