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 msg = f'Unhandled top level exception {exc_type}'
48 print(msg, file=sys.stderr)
49 if issubclass(exc_type, KeyboardInterrupt):
50 sys.__excepthook__(exc_type, exc_value, exc_tb)
54 not sys.stderr.isatty() or
55 not sys.stdin.isatty()
57 # stdin or stderr is redirected, just do the normal thing
58 original_hook(exc_type, exc_value, exc_tb)
60 # a terminal is attached and stderr is not redirected, debug.
61 if config.config['debug_unhandled_exceptions']:
64 traceback.print_exception(exc_type, exc_value, exc_tb)
65 logger.info("Invoking the debugger...")
68 original_hook(exc_type, exc_value, exc_tb)
71 def initialize(entry_point):
73 """Remember to initialize config and logging before running main."""
74 @functools.wraps(entry_point)
75 def initialize_wrapper(*args, **kwargs):
76 if sys.excepthook == sys.__excepthook__:
77 sys.excepthook = handle_uncaught_exception
79 '__globals__' in entry_point.__dict__ and
80 '__file__' in entry_point.__globals__
82 config.parse(entry_point.__globals__['__file__'])
86 logging_utils.initialize_logging(logging.getLogger())
90 # Allow programs that don't bother to override the random seed
91 # to be replayed via the commandline.
93 random_seed = config.config['set_random_seed']
94 if random_seed is not None:
95 random_seed = random_seed[0]
97 random_seed = int.from_bytes(os.urandom(4), 'little')
99 if config.config['show_random_seed']:
100 msg = f'Global random seed is: {random_seed}'
103 random.seed(random_seed)
105 logger.debug(f'Starting {entry_point.__name__} (program entry point)')
109 with stopwatch.Timer() as t:
110 ret = entry_point(*args, **kwargs)
112 f'{entry_point.__name__} (program entry point) returned {ret}.'
116 (utime, stime, cutime, cstime, elapsed_time) = os.times()
119 f'system: {stime}s\n'
120 f'child user: {cutime}s\n'
121 f'child system: {cstime}s\n'
122 f'machine uptime: {elapsed_time}s\n'
123 f'walltime: {walltime}s')
124 if ret is not None and ret != 0:
125 logger.error(f'Exit {ret}')
127 logger.debug(f'Exit {ret}')
129 return initialize_wrapper