32

考虑

try:
   import someProprietaryModule
except ImportError:
   raise ImportError('It appears that <someProprietaryModule> is not installed...')

运行时,如果 someProprietaryModule 未安装,则会看到:

(traceback data)
ImportError: unknown module: someProprietaryModule

During handling of the above exception, another exception occurred:

(traceback data)
ImportError: It appears that <someProprietaryModule> is not installed...

也许我不希望出现“在处理上述异常期间......”行(以及它上面的行)。我可以这样做:

_moduleInstalled = True
try:
   import someProprietaryModule
except ImportError:
   _moduleInstalled = False
if not _moduleInstalled: 
   raise ImportError('It appears that <someProprietaryModule> is not installed...')

但这感觉有点像黑客。我还能做什么?

4

3 回答 3

52

在 Python 3.3 及更高版本raise ... from None中可能会在这种情况下使用。

try:
   import someProprietaryModule
except ImportError:
   raise ImportError('It appears that <someProprietaryModule> is not installed...') from None

这具有预期的结果。

于 2013-06-13T16:15:09.813 回答
2

这可以在 Python 2.7 和 Python 3 中像这样完成:

try:
    import someProprietaryModule
except ImportError as e:
    raised_error = e

if isinstance(raised_error, ImportError):
    raise ImportError('It appears that <someProprietaryModule> is not installed...')
于 2017-12-14T15:42:43.463 回答
0

您也可以尝试logging模块

import logging

try:
    import someProprietaryModule
    
except Exception as e:
    
    if hasattr(e, 'message'):
        logging.warning('python2')
        logging.error(e.message)
        
    else:
        
        logging.warning('python3')
        logging.error('It appears that <someProprietaryModule> is not installed...')

WARNING:root:python3
ERROR:root:It appears that <someProprietaryModule> is not installed...

[Program finished]
于 2021-06-04T19:07:29.043 回答