[英]Raise an exception at import if conditions not met
I have a module that depends on some system settings. 我有一个依赖于某些系统设置的模块。 For example, to work properly it needs to have an environment variable FOO set.
例如,要正常工作,需要设置环境变量FOO。 I would like the module to raise an Exception if this condition is not met at import time.
如果导入时未满足此条件,我希望模块引发Exception。
# mymodule.py
if 'FOO' not in sys.environ:
raise SomeException('ensure that FOO is provided')
I would like to know: 我想知道:
class MyModuleImportError(Exception)
or maybe some built-in exceptions are more suitable and commonly used? class MyModuleImportError(Exception)
还是某些内置的异常更合适且更常用? One candidate would be ImportError , but it seems to be reserved for situation when python "fails to find the module definition" Is this what you are looking for? 这是你想要的?
>>> import os
>>> if not os.getenv('FOO', False):
raise OSError('FOO not in envs')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.