@@ -240,15 +240,19 @@ def get_message_lines(typ, exc, tb):
240240 return traceback .format_exception_only (typ , exc )
241241
242242
243- def print_exception ():
243+ def print_exception (in_test = False ):
244244 import linecache
245245 linecache .checkcache ()
246246 flush_stdout ()
247- efile = sys .stderr
247+ if not in_test :
248+ efile = sys .stderr
249+ else :
250+ efile = io .StringIO ()
248251 typ , val , tb = excinfo = sys .exc_info ()
249252 sys .last_type , sys .last_value , sys .last_traceback = excinfo
250253 sys .last_exc = val
251254 seen = set ()
255+ err = io .StringIO ()
252256
253257 def print_exc (typ , exc , tb ):
254258 seen .add (id (exc ))
@@ -274,12 +278,14 @@ def print_exc(typ, exc, tb):
274278 if ((not isinstance (exc , NameError ) and not isinstance (exc , AttributeError ))
275279 or "\n " not in str (exc )):
276280 lines = get_message_lines (typ , exc , tb )
277- else : # User-created Name/AttributeError with multiline message, GH-135511.
278- lines = [f"{ typ .__name__ } : { str (exc )} " ]
281+ else :
282+ lines = [f"{ typ .__name__ } : { str (exc )} " ]
279283 for line in lines :
280284 print (line , end = '' , file = efile )
285+ print (line , end = '' , file = err )
281286
282287 print_exc (typ , val , tb )
288+ return err .getvalue ()
283289
284290def cleanup_traceback (tb , exclude ):
285291 "Remove excluded traces from beginning/end of tb; get cached lines"
0 commit comments