bpo-33809: add the TracebackException.print() method (GH-24231)

This commit is contained in:
Irit Katriel 2021-05-22 17:39:33 +01:00 committed by GitHub
parent 9e746e3298
commit 220dd80a26
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 34 additions and 4 deletions

View file

@ -271,6 +271,13 @@ capture data for later printing in a lightweight fashion.
Note that when locals are captured, they are also shown in the traceback. Note that when locals are captured, they are also shown in the traceback.
.. method:: print(*, file=None, chain=True)
Print to *file* (default ``sys.stderr``) the exception information returned by
:meth:`format`.
.. versionadded:: 3.11
.. method:: format(*, chain=True) .. method:: format(*, chain=True)
Format the exception. Format the exception.

View file

@ -1378,6 +1378,23 @@ class TestTracebackException(unittest.TestCase):
exc = traceback.TracebackException(Exception, Exception("haven"), None) exc = traceback.TracebackException(Exception, Exception("haven"), None)
self.assertEqual(list(exc.format()), ["Exception: haven\n"]) self.assertEqual(list(exc.format()), ["Exception: haven\n"])
def test_print(self):
def f():
x = 12
try:
x/0
except Exception:
return sys.exc_info()
exc = traceback.TracebackException(*f(), capture_locals=True)
output = StringIO()
exc.print(file=output)
self.assertEqual(
output.getvalue().split('\n')[-4:],
[' x/0',
' x = 12',
'ZeroDivisionError: division by zero',
''])
class MiscTest(unittest.TestCase): class MiscTest(unittest.TestCase):

View file

@ -111,11 +111,8 @@ def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
position of the error. position of the error.
""" """
value, tb = _parse_value_tb(exc, value, tb) value, tb = _parse_value_tb(exc, value, tb)
if file is None:
file = sys.stderr
te = TracebackException(type(value), value, tb, limit=limit, compact=True) te = TracebackException(type(value), value, tb, limit=limit, compact=True)
for line in te.format(chain=chain): te.print(file=file, chain=chain)
print(line, file=file, end="")
def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \ def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
@ -669,3 +666,10 @@ class TracebackException:
yield 'Traceback (most recent call last):\n' yield 'Traceback (most recent call last):\n'
yield from exc.stack.format() yield from exc.stack.format()
yield from exc.format_exception_only() yield from exc.format_exception_only()
def print(self, *, file=None, chain=True):
"""Print the result of self.format(chain=chain) to 'file'."""
if file is None:
file = sys.stderr
for line in self.format(chain=chain):
print(line, file=file, end="")

View file

@ -0,0 +1,2 @@
Add the :meth:`traceback.TracebackException.print` method which prints
the formatted exception information.