8 # This module is commonly used by others in here and should avoid
9 # taking any unnecessary dependencies back on them.
11 from argparse_utils import ActionNoYes
15 logger = logging.getLogger(__name__)
17 args = config.add_commandline_args(
18 f'Bootstrap ({__file__})',
19 'Args related to python program bootstrapper and Swiss army knife')
21 '--debug_unhandled_exceptions',
24 help='Break into pdb on top level unhandled exceptions.'
30 help='Should we display (and log.debug) the global random seed?'
38 help='Override the global random seed with a particular number.'
41 original_hook = sys.excepthook
44 def handle_uncaught_exception(exc_type, exc_value, exc_tb):
46 Top-level exception handler for exceptions that make it past any exception
47 handlers in the python code being run. Logs the error and stacktrace then
48 maybe attaches a debugger.
51 msg = f'Unhandled top level exception {exc_type}'
53 print(msg, file=sys.stderr)
54 if issubclass(exc_type, KeyboardInterrupt):
55 sys.__excepthook__(exc_type, exc_value, exc_tb)
59 not sys.stderr.isatty() or
60 not sys.stdin.isatty()
62 # stdin or stderr is redirected, just do the normal thing
63 original_hook(exc_type, exc_value, exc_tb)
65 # a terminal is attached and stderr is not redirected, maybe debug.
67 traceback.print_exception(exc_type, exc_value, exc_tb)
68 if config.config['debug_unhandled_exceptions']:
70 logger.info("Invoking the debugger...")
73 original_hook(exc_type, exc_value, exc_tb)
76 def initialize(entry_point):
78 Remember to initialize config, initialize logging, set/log a random
79 seed, etc... before running main.
82 @functools.wraps(entry_point)
83 def initialize_wrapper(*args, **kwargs):
85 # Hook top level unhandled exceptions, maybe invoke debugger.
86 if sys.excepthook == sys.__excepthook__:
87 sys.excepthook = handle_uncaught_exception
89 # Try to figure out the name of the program entry point. Then
90 # parse configuration (based on cmdline flags, environment vars
93 '__globals__' in entry_point.__dict__ and
94 '__file__' in entry_point.__globals__
96 config.parse(entry_point.__globals__['__file__'])
100 # Initialize logging... and log some remembered messages from
102 logging_utils.initialize_logging(logging.getLogger())
103 config.late_logging()
105 # Allow programs that don't bother to override the random seed
106 # to be replayed via the commandline.
108 random_seed = config.config['set_random_seed']
109 if random_seed is not None:
110 random_seed = random_seed[0]
112 random_seed = int.from_bytes(os.urandom(4), 'little')
114 if config.config['show_random_seed']:
115 msg = f'Global random seed is: {random_seed}'
118 random.seed(random_seed)
120 # Do it, invoke the user's code. Pay attention to how long it takes.
121 logger.debug(f'Starting {entry_point.__name__} (program entry point)')
124 with stopwatch.Timer() as t:
125 ret = entry_point(*args, **kwargs)
127 f'{entry_point.__name__} (program entry point) returned {ret}.'
131 (utime, stime, cutime, cstime, elapsed_time) = os.times()
134 f'system: {stime}s\n'
135 f'child user: {cutime}s\n'
136 f'child system: {cstime}s\n'
137 f'machine uptime: {elapsed_time}s\n'
138 f'walltime: {walltime}s')
140 # If it doesn't return cleanly, call attention to the return value.
141 if ret is not None and ret != 0:
142 logger.error(f'Exit {ret}')
144 logger.debug(f'Exit {ret}')
146 return initialize_wrapper