Python exception handler to recommend package Consider this python 3 snippet, where when an import exception is raised, a string 'e' is created that says: "No module named ' packageName'".

The goal is to simply say on exit, that the import error can perhaps be solved by installing a package of the same name. I came up with this, and it works but I'd like to make it better, if anyone has some tips.

except ImportError as e:
     e = e.replace("No module named '", "")
     e = e.replace("'", "")
     sys.exit("'Error: Try sudo pip install %s'" % e)


Example output:


  Error: Try sudo pip install Crypto
An ImportError instance doesn't have a replace method.

You can use e.name instead of messy string replacements.



Instead of '%s' % x, it's recommended to use '{}'.format(x).



The example output is not what you posted, but actually this:


  'Error: Try sudo pip install Crypto'


That is, it's surrounded by single quotes, because you wrote as "'some text'".
Probably you want to remove those single quotes inside the string.



What does the message even mean?

This would make a lot more sense:


  Error: could not import 'Crypto'. Try installing with: pip install --user Crypto




Last, but most importantly, please don't recommend to install Python packages system-wide. This is a more sensible recommendation:

pip install --user the_package


This doesn't need sudo, as it will install the package in the user's home directory, not system-wide.



Putting it together:

try:
    import somename
except ImportError as e:
    sys.exit("Error: could not import '{0}'. Try installing with: pip install --user {0}".format(e.name))