【发布时间】:2018-11-11 23:42:35
【问题描述】:
下面的玩具脚本说明了这个问题:
#!/usr/bin/env python3
def bomb():
"""
>>> bomb()
Traceback (most recent call last):
File "<string>", line 18, in bomb
ZeroDivisionError: division by zero
<BLANKLINE>
During handling of the above exception, another exception occurred:
<BLANKLINE>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 20, in bomb
Exception: re-raised
"""
try:
1/0
except Exception as exception:
raise Exception('re-raised')
if __name__ == '__main__' and '__file__' in globals():
import sys
if len(sys.argv) > 1 and sys.argv[1] == '-t':
import doctest
doctest.testmod()
else:
bomb()
如果我在 python 解释器中执行bomb(),我会得到文档字符串指定的输出:
% python3
Python 3.5.1 (default, May 24 2016, 20:04:39)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exec(open('demo.py').read())
>>> bomb()
Traceback (most recent call last):
File "<string>", line 18, in bomb
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 20, in bomb
Exception: re-raised
>>>
但是,doctest 错误地报告失败:
**********************************************************************
File "./demo.py", line 5, in __main__.bomb
Failed example:
bomb()
Expected:
Traceback (most recent call last):
File "<string>", line 16, in bomb
ZeroDivisionError: division by zero
<BLANKLINE>
During handling of the above exception, another exception occurred:
<BLANKLINE>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 18, in bomb
Exception: re-raised
Got:
Traceback (most recent call last):
File "./demo.py", line 18, in bomb
1/0
ZeroDivisionError: division by zero
<BLANKLINE>
During handling of the above exception, another exception occurred:
<BLANKLINE>
Traceback (most recent call last):
File "/usr/lib/python3.5/doctest.py", line 1320, in __run
compileflags, 1), test.globs)
File "<doctest __main__.bomb[0]>", line 1, in <module>
bomb()
File "./demo.py", line 20, in bomb
【问题讨论】:
标签: python python-3.x exception doctest