【发布时间】:2018-11-24 23:14:05
【问题描述】:
当os.environ 被赋予一个未设置的环境变量的名称时,它会抛出一个KeyError:
In [1]: my_value = os.environ['SOME_VALUE']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-6-0573debe183e> in <module>()
----> 1 my_value = os.environ['SOME_VALUE']
~/blah/ve/lib/python3.6/os.py in __getitem__(self, key)
667 except KeyError:
668 # raise KeyError with the original key value
--> 669 raise KeyError(key) from None
670 return self.decodevalue(value)
671
KeyError: 'SOME_VALUE'
我知道KeyError 被引发,因为os.environ 就像一个字典,但是在需要设置SOME_VALUE 的应用程序中,当用户忽略设置它时,我想引发更多信息错误.一种选择是提出EnvironmentError 并提供更多信息:
try:
my_value = os.environ['SOME_VALUE']
except KeyError:
raise EnvironmentError('SOME_VALUE environment variable needs to be set to import this module') from KeyError
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
KeyError:
The above exception was the direct cause of the following exception:
OSError Traceback (most recent call last)
<ipython-input-10-406772b14ea9> in <module>()
2 my_value = os.environ['SOME_VALUE']
3 except KeyError:
----> 4 raise EnvironmentError('SOME_VALUE environment variable not set') from KeyError
OSError: SOME_VALUE environment variable not set
我很好奇这会引发OSError。 Python 2.7 文档说EnvironmentError 是OSError 的基类,并且基异常“...仅用作其他异常的基类”。在 Python 3.6 文档中,EnvironmentError is listed among concrete exceptions,但没有任何关于错误类本身的文档。问题:
- 在这种情况下使用
EnvironmentError是否合适?我应该使用其他一些内置错误,还是自定义错误? -
EnvironmentError是 Python 3.6 中的基本错误类吗? - 为什么
OSError而不是EnvironmentError被提升?
【问题讨论】:
-
您的问题 2 和 3 实际上已在您的链接中得到解答,就在锚点上方:
The following exceptions are kept for compatibility with previous versions; starting from Python 3.3, they are aliases of OSError.。如果您不想使用/查看 OSError,请创建自己的。但是,我会坚持使用 OSError,它在这种情况下似乎很合适。鉴于 EnvironmentError 只是为了在 Python >= 3.3 中保持兼容性,我认为它在 Python 3.6 中的使用不合适。
标签: python python-3.x error-handling environment-variables