python exception handler to recomend package
Question: I would like to have python recomend a python package in the event of an
import error.

I tried:

    
    
    except ImportError as e:
         sys.exit("'Error: Try sudo pip install %s'" % e)
    

but this is the output:

    
    
    'Error: Try sudo pip install No module named 'Crypto'' 
    

I would like the output to be:

    
    
    'Error: Try sudo pip install Crypto' 
    

how can I do that?

Update: it pretty hacky, but here is something that seems to work:

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

If someone has a better solution, I'd love to hear about it.


Answer: Use `ImportError.name`

    
    
    >>> try:
    ...     import fakecrypto
    ... except ImportError as e:
    ...     ex = e
    ... 
    >>> dir(ex)
    ['__cause__', '__class__', '__context__', '__delattr__', '__dict__', 
    '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
    '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
    '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
    '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__',
    '__subclasshook__', '__suppress_context__', '__traceback__', 'args',
    'msg', 'name', 'path', 'with_traceback']
    >>> ex.name
    'fakecrypto'
    

