ModuleNotFoundError: No module named 'CommandNotFound'

Whenever I try

sudo apt update

I got:

Traceback (most recent call last):
  File "/usr/lib/cnf-update-db", line 8, in <module>
    from CommandNotFound.db.creator import DbCreator
ModuleNotFoundError: No module named 'CommandNotFound'
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

Any suggestions?
Pei

This sounds like you have broken your system installation of Python. I
guess you are running Linux, from the use of “sudo”. Which distro are
you using?

I am surprised that apt seems to be using Python. I knew yum (Redhat
distros) uses Python, I thought apt was a C++ application.

You may have better success on a forum specific for your distro, but if
I were you, I would start with:

sudo which apt

to find out what you are actually running. If it is a Python script, you
can probably tell what version of Python it is expecting from the
hashbang line at the top of the script, for example:

#!/usr/local/bin/python2.7

Then check to see if you have replaced the expected Python libs.

Naturally don’t edit the apt script unless you know what you are doing!

Thank you for your prompt reply…

➜  ~ sudo which apt
/usr/bin/apt

You are right. My OS is Ubuntu 18.04.3, and I’m NOT using system Python 3.7.3 installed from the repository. I actually manually installed my own Python 3.8.1 .

I abandoned Python2.7 thoroughly.

Any further suggestions?

Pei

You should never manually change the system python! If the OS needs a

certain version, it needs that version.

Hopefully you still have the system Python 3.7.3 or Python2.7 and

haven’t completely removed it. Try:

which python3.7

and see if that still comes up. Then try:

which python

and hopefully it will be an alias like:

/usr/bin/python -> /usr/bin/python3.8

or something similar. Then change the alias /usr/bin/python back to

your old Python 3.7 or 2.7 installation, whichever Ubuntu needs, and

hopefully apt will work again.

But you really should ask some Ubuntu experts about this. I’m still

confused why apt is using Python in the first place.

Finally, once everything is working again, create an alias in your

shell. If you use bash, add this to .bash.rc in your home directory:

alias python='python3.8'

and when you next log in, the “python” command should run 3.8 for you

but not the OS.

alias python=‘python3.8’

added and sourced, same error

➜  ~ sudo apt update
......
Fetched 1,967 kB in 2s (1,258 kB/s)                  
Traceback (most recent call last):
  File "/usr/lib/cnf-update-db", line 8, in <module>
    from CommandNotFound.db.creator import DbCreator
ModuleNotFoundError: No module named 'CommandNotFound'
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

It looks py3compile is not installed from my manually installed python3.8.1.

Don’t add an alias python -> python3.8 until you have fixed everything

else. A personal alias is not going to fix a system-wide breakage.

What version of Python is apt trying to use? That’s an Ubuntu question,

not a Python question.

Once you know what version of Python apt needs you need to revert to

using that version by default.

Hopefully you haven’t destroyed or overwritten the system Python,

and all the dependencies used by apt. If you have destroyed them, I don’t know what

you need to do. Reinstall the OS maybe? Ask an Ubuntu forum. But if you

are lucky, it’s just a PATH issue, maybe.

You might be able to repair apt if apt-get is working. See here:

Failed to install Python 3.8.1 under pyenv.

➜  ~ pyenv install -v 3.8.1
......
ERROR: Exception:
Traceback (most recent call last):
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_internal/cli/base_command.py", line 188, in main
    status = self.run(options, args)
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_internal/commands/install.py", line 286, in run
    with self._build_session(options) as session:
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_internal/cli/base_command.py", line 101, in _build_session
    session = PipSession(
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_internal/download.py", line 559, in __init__
    self.headers["User-Agent"] = user_agent()
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_internal/download.py", line 144, in user_agent
    zip(["name", "version", "id"], distro.linux_distribution()),
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_vendor/distro.py", line 122, in linux_distribution
    return _distro.linux_distribution(full_distribution_name)
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_vendor/distro.py", line 677, in linux_distribution
    self.version(),
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_vendor/distro.py", line 737, in version
    self.lsb_release_attr('release'),
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_vendor/distro.py", line 899, in lsb_release_attr
    return self._lsb_release_info.get(attribute, '')
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_vendor/distro.py", line 552, in __get__
    ret = obj.__dict__[self._fname] = self._f(obj)
  File "/tmp/tmp6a9wsa3z/pip-19.2.3-py2.py3-none-any.whl/pip/_vendor/distro.py", line 1012, in _lsb_release_info
    stdout = subprocess.check_output(cmd, stderr=devnull)
  File "/tmp/python-build.20200222120905.3660/Python-3.8.1/Lib/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/tmp/python-build.20200222120905.3660/Python-3.8.1/Lib/subprocess.py", line 512, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '('lsb_release', '-a')' died with <Signals.SIGABRT: 6>.
Makefile:1186: recipe for target 'install' failed
make: *** [install] Error 2

BUILD FAILEDCould not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f597cccd340 (most recent call first):
 ( using python-build 1.2.16-5-g7097f820)

Inspect or clean up the working tree at /tmp/python-build.20200222120905.3660
Results logged to /tmp/python-build.20200222120905.3660.log

Last 10 log lines:
subprocess.CalledProcessError: Command '('lsb_release', '-a')' died with <Signals.SIGABRT: 6>.
Makefile:1186: recipe for target 'install' failed
make: *** [install] Error 2
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f597cccd340 (most recent call first):
➜

Have you fixed the issue with the system Python yet?

Until you fix that, trying to reinstall Python 3.8 in another fashion is

at best irrelevant and at worst making the problem worse.

We’re very gratified that you are desperate to use the latest and

greatest Python version, but you really ought to stop thinking about 3.8

now and start thinking about repairing your broken OS.

Did you try using apt-get, as explained in the Stackoverflow post I

linked to earlier?

To clarify the situation:

  • the heart of Debian packaging is dpkg, which validates and installs deb packages; validates = check version, architecture, dependencies, conflicts; installs = put files in the right places and run maintainer scripts (to update configs, services, databases, etc)
  • APT is a layer on top that deals with repositories and downloads
  • to use the APT system, one invokes a front-end program such as apt-get, aptitude, a graphical package manager, or apt (recent command-line program that replaces apt-get, apt-cache, apt-show, etc)

Now if we look at the error message closely:

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'

This shows that APT, like dpkg, has hooks to run various programs before and after installing, updating or removing packages, for example apt-listbugs (written in ruby) to show known bugs in the new versions and give the operator a chance to change their mind. Here the program is command-not-found, which is a utility (written in python) invoked by the shell to show hints like this:

$ mplayer

Command 'mplayer' not found, but can be installed with:

apt install mplayer
Please ask your administrator.

The database used by command-not-found is updated when the APT package database is updated.
This is the command that fails on your system, probably because something messed up your system Python and causes the import to fail. You should follow the advice given by Steven and fix your OS, reinstalling (using apt or another frontend) the python3 and command-not-found packages. If the reinstall command fails because command-not-found is broken, edit /etc/apt/apt.conf.d/50-command-not-found to comment the script temporarily.

Hope this helps!

1 Like

Hi i just had same problem and i managed to solve it by editing
/usr/lib/cnf-update-db
i changed the interpreter from /usr/bin/python3 to /usr/bin/python3.6