summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rw-r--r--Lib/test/test_traceback.py17
-rw-r--r--Lib/traceback.py12
2 files changed, 25 insertions, 4 deletions
diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py
index 5bd969d..e9df1ce 100644
--- a/Lib/test/test_traceback.py
+++ b/Lib/test/test_traceback.py
@@ -1378,6 +1378,23 @@ class TestTracebackException(unittest.TestCase):
exc = traceback.TracebackException(Exception, Exception("haven"), None)
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):
diff --git a/Lib/traceback.py b/Lib/traceback.py
index 8f908dd..e19745d 100644
--- a/Lib/traceback.py
+++ b/Lib/traceback.py
@@ -111,11 +111,8 @@ def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
position of the error.
"""
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)
- for line in te.format(chain=chain):
- print(line, file=file, end="")
+ te.print(file=file, chain=chain)
def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
@@ -669,3 +666,10 @@ class TracebackException:
yield 'Traceback (most recent call last):\n'
yield from exc.stack.format()
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="")