Python - No module named CommandNotFound

All Gurus once were Newbies
Forum rules
There are no such things as "stupid" questions. However if you think your question is a bit stupid, then this is the right place for you to post it. Please stick to easy to-the-point questions that you feel people can answer fast. For long and complicated questions prefer the other forums within the support section.
Before you post please read how to get help
Post Reply
wingedearth
Level 1
Level 1
Posts: 29
Joined: Tue Feb 18, 2014 1:32 am

Python - No module named CommandNotFound

Post by wingedearth » Tue Apr 05, 2016 1:53 pm

Help, I'm getting an "ImportError: No module named 'CommandNotFound'" when running a python test.
The error indicates that it results from Line 27 of usr/lib/command-not-found, which reads:

Code: Select all

from CommandNotFound.util import crash_guard
From what I've seen on Google, this has to do with an installation issue from having both Python 2 and Python 3 installed, but the solutions I found on linuxforums do not resolve the problem. Please help.

wingedearth
Level 1
Level 1
Posts: 29
Joined: Tue Feb 18, 2014 1:32 am

Re: Python - No module named CommandNotFound

Post by wingedearth » Tue Apr 05, 2016 1:54 pm

Here's my usr/lib/command-not-found file:

Code: Select all

#!/usr/bin/python3
# (c) Zygmunt Krynicki 2005, 2006, 2007, 2008
# Licensed under GPL, see COPYING for the whole text

from __future__ import absolute_import, print_function


__version__ = "0.3"
BUG_REPORT_URL = "https://bugs.launchpad.net/command-not-found/+filebug"

try:
    import sys
    if sys.path and sys.path[0] == '/usr/lib':
        # Avoid ImportError noise due to odd installation location.
        sys.path.pop(0)
    if sys.version < '3':
        # We might end up being executed with Python 2 due to an old
        # /etc/bash.bashrc.
        import os
        if "COMMAND_NOT_FOUND_FORCE_PYTHON2" not in os.environ:
            os.execvp("python3.5", [sys.argv[0]] + sys.argv)

    import gettext
    import locale
    from optparse import OptionParser

    from CommandNotFound.util import crash_guard
    from CommandNotFound import CommandNotFound
except KeyboardInterrupt:
    import sys
    sys.exit(127)


def enable_i18n():
    cnf = gettext.translation("command-not-found", fallback=True)
    kwargs = {}
    if sys.version < '3':
        kwargs["unicode"] = True
    cnf.install(**kwargs)
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error:
        locale.setlocale(locale.LC_ALL, 'C')


def fix_sys_argv(encoding=None):
    """
    Fix sys.argv to have only unicode strings, not binary strings.
    This is required by various places where such argument might be
    automatically coerced to unicode string for formatting
    """
    if encoding is None:
        encoding = locale.getpreferredencoding()
    sys.argv = [arg.decode(encoding) for arg in sys.argv]


class LocaleOptionParser(OptionParser):
    """
    OptionParser is broken as its implementation of _get_encoding() uses
    sys.getdefaultencoding() which is ascii, what it should be using is
    locale.getpreferredencoding() which returns value based on LC_CTYPE (most
    likely) and allows for UTF-8 encoding to be used.
    """
    def _get_encoding(self, file):
        encoding = getattr(file, "encoding", None)
        if not encoding:
            encoding = locale.getpreferredencoding()
        return encoding


def main():
    enable_i18n()
    if sys.version < '3':
        fix_sys_argv()
    parser = LocaleOptionParser(
        version=__version__,
        usage=_("%prog [options] <command-name>"))
    parser.add_option('-d', '--data-dir', action='store',
                      default="/usr/share/command-not-found",
                      help=_("use this path to locate data fields"))
    parser.add_option('--ignore-installed', '--ignore-installed',
                      action='store_true',  default=False,
                      help=_("ignore local binaries and display the available packages"))
    parser.add_option('--no-failure-msg',
                      action='store_true', default=False,
                      help=_("don't print '<command-name>: command not found'"))
    (options, args) = parser.parse_args()
    if len(args) == 1:
        cnf = CommandNotFound(options.data_dir)
        if not cnf.advise(args[0], options.ignore_installed) and not options.no_failure_msg:
            print(_("%s: command not found") % args[0], file=sys.stderr)

if __name__ == "__main__":
    crash_guard(main, BUG_REPORT_URL, __version__)

wingedearth
Level 1
Level 1
Posts: 29
Joined: Tue Feb 18, 2014 1:32 am

Re: Python - No module named CommandNotFound

Post by wingedearth » Tue Apr 05, 2016 1:55 pm

And if it helps, here's my /etc/bash.bashrc file:

Code: Select all

# System-wide .bashrc file for interactive bash(1) shells.

# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

use_color=false

# Set colorful PS1 only on colorful terminals.
# dircolors --print-database uses its own built-in database
# instead of using /etc/DIR_COLORS.  Try to use the external file
# first to take advantage of user additions.  Use internal bash
# globbing instead of external grep binary.
safe_term=${TERM//[^[:alnum:]]/?}   # sanitize TERM
match_lhs=""
[[ -f ~/.dir_colors   ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
[[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
[[ -z ${match_lhs}    ]] \
        && type -P dircolors >/dev/null \
        && match_lhs=$(dircolors --print-database)
[[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true

if ${use_color} ; then
        # Enable colors for ls, etc.  Prefer ~/.dir_colors #64489
        if type -P dircolors >/dev/null ; then
                if [[ -f ~/.dir_colors ]] ; then
                        eval $(dircolors -b ~/.dir_colors)
                elif [[ -f /etc/DIR_COLORS ]] ; then
                        eval $(dircolors -b /etc/DIR_COLORS)
        else
            eval $(dircolors)
                fi
        fi

        if [[ ${EUID} == 0 ]] ; then
                PS1='${debian_chroot:+($debian_chroot)}\[\033[01;31m\]\h\[\033[01;34m\] \W \$\[\033[00m\] '
        else
                PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
        fi

        alias ls='ls --color=auto'
        alias grep='grep --colour=auto'
        alias fgrep='fgrep --color=auto'
        alias egrep='egrep --color=auto'
else
        if [[ ${EUID} == 0 ]] ; then
                # show root@ when we don't have colors
                PS1='\u@\h \W \$ '
        else
                PS1='\u@\h \w \$ '
        fi
fi

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# Try to keep environment pollution down, EPA loves us.
unset use_color safe_term match_lhs

# Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.
# If this is an xterm set the title to user@host:dir
#case "$TERM" in
#xterm*|rxvt*)
#    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
#    ;;
#*)
#    ;;
#esac

# enable bash completion in interactive shells
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
    function command_not_found_handle {
            # check because c-n-f could've been removed in the meantime
                if [ -x /usr/lib/command-not-found ]; then
           /usr/lib/command-not-found -- "$1"
                   return $?
                elif [ -x /usr/share/command-not-found/command-not-found ]; then
           /usr/share/command-not-found/command-not-found -- "$1"
                   return $?
        else
           printf "%s: command not found\n" "$1" >&2
           return 127
        fi
    }
fi

if [ -x /usr/bin/mint-fortune ]; then
    /usr/bin/mint-fortune
fi

export PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[01;33m\]$(__git_ps1)\[\033[01;34m\] \$\[\033[00m\] '

wingedearth
Level 1
Level 1
Posts: 29
Joined: Tue Feb 18, 2014 1:32 am

Re: Python - No module named CommandNotFound

Post by wingedearth » Tue Apr 05, 2016 8:03 pm

Has anyone had this sort of error with Python's CommandNotFound module running on Linux? Does anyone know how to resolve this?

Post Reply

Return to “Newbie Questions”