@@ -133,7 +133,7 @@ def __init__(self, stmt="pass", setup="pass", timer=default_timer,
133133 exec (code , global_ns , local_ns )
134134 self .inner = local_ns ["inner" ]
135135
136- def print_exc (self , file = None ):
136+ def print_exc (self , file = None , ** kwargs ):
137137 """Helper to print a traceback from the timed code.
138138
139139 Typical use:
@@ -149,6 +149,11 @@ def print_exc(self, file=None):
149149
150150 The optional file argument directs where the traceback is
151151 sent; it defaults to sys.stderr.
152+
153+ The optional colorize keyword argument controls whether the
154+ traceback is colorized; it defaults to False for programmatic
155+ usage. When used from the command line, this is automatically
156+ set based on terminal capabilities.
152157 """
153158 import linecache , traceback
154159 if self .src is not None :
@@ -158,7 +163,8 @@ def print_exc(self, file=None):
158163 dummy_src_name )
159164 # else the source is already stored somewhere else
160165
161- traceback .print_exc (file = file )
166+ kwargs ['colorize' ] = kwargs .get ('colorize' , False )
167+ traceback .print_exc (file = file , ** kwargs )
162168
163169 def timeit (self , number = default_number ):
164170 """Time 'number' executions of the main statement.
@@ -257,9 +263,12 @@ def main(args=None, *, _wrap_timer=None):
257263 is not None, it must be a callable that accepts a timer function
258264 and returns another timer function (used for unit testing).
259265 """
266+ import getopt
260267 if args is None :
261268 args = sys .argv [1 :]
262- import getopt
269+ import _colorize
270+ colorize = _colorize .can_colorize ()
271+
263272 try :
264273 opts , args = getopt .getopt (args , "n:u:s:r:pvh" ,
265274 ["number=" , "setup=" , "repeat=" ,
@@ -326,7 +335,7 @@ def callback(number, time_taken):
326335 try :
327336 number , _ = t .autorange (callback )
328337 except :
329- t .print_exc ()
338+ t .print_exc (colorize = colorize )
330339 return 1
331340
332341 if verbose :
@@ -335,7 +344,7 @@ def callback(number, time_taken):
335344 try :
336345 raw_timings = t .repeat (repeat , number )
337346 except :
338- t .print_exc ()
347+ t .print_exc (colorize = colorize )
339348 return 1
340349
341350 def format_time (dt ):
0 commit comments