Следующий игрушечный скрипт иллюстрирует проблему:
#!/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()
Если я выполню bomb()
в интерпретаторе python, я получу вывод, указанный строкой документации:
% 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