我想在导入错误的情况下让python推荐一个python包。
我试过了:
except ImportError as e:
sys.exit("'Error: Try sudo pip install %s'" % e)
但这是输出:
'Error: Try sudo pip install No module named 'Crypto''
我希望输出为:
'Error: Try sudo pip install Crypto'
我该怎么做?
更新: 它非常hacky,但这里似乎有用:
except ImportError as e:
e = e.replace("No module named '", "")
e = e.replace("'", "")
sys.exit("'Error: Try sudo pip install %s'" % e)
答案 0 :(得分:1)
使用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'