94c8e9c0ecde3347832276d0a2177dd9ee76a410
[python_utils.git] / bootstrap.py
1 #!/usr/bin/env python3
2
3 import functools
4 import logging
5 import os
6 import sys
7 import time
8 import traceback
9
10 import argparse_utils
11 import config
12
13
14 logger = logging.getLogger(__name__)
15
16 args = config.add_commandline_args(
17     f'Bootstrap ({__file__})',
18     'Args related to python program bootstrapper and Swiss army knife')
19 args.add_argument(
20     '--debug_unhandled_exceptions',
21     action=argparse_utils.ActionNoYes,
22     default=False,
23     help='Break into debugger on top level unhandled exceptions for interactive debugging'
24 )
25
26
27 def handle_uncaught_exception(
28         exc_type,
29         exc_value,
30         exc_traceback):
31     if issubclass(exc_type, KeyboardInterrupt):
32         sys.__excepthook__(exc_type, exc_value, exc_traceback)
33         return
34     logger.exception(f'Unhandled top level {exc_type}',
35                      exc_info=(exc_type, exc_value, exc_traceback))
36     traceback.print_exception(exc_type, exc_value, exc_traceback)
37     if config.config['debug_unhandled_exceptions']:
38         logger.info("Invoking the debugger...")
39         breakpoint()
40
41
42 def initialize(funct):
43     import logging_utils
44
45     """Remember to initialize config and logging before running main."""
46     @functools.wraps(funct)
47     def initialize_wrapper(*args, **kwargs):
48         sys.excepthook = handle_uncaught_exception
49         config.parse()
50         logging_utils.initialize_logging(logging.getLogger())
51         config.late_logging()
52         logger.debug(f'Starting {funct.__name__}')
53         start = time.perf_counter()
54         ret = funct(*args, **kwargs)
55         end = time.perf_counter()
56         logger.debug(f'{funct} returned {ret}.')
57         (utime, stime, cutime, cstime, elapsed_time) = os.times()
58         logger.debug(f'\nuser: {utime}s\n'
59                      f'system: {stime}s\n'
60                      f'child user: {cutime}s\n'
61                      f'child system: {cstime}s\n'
62                      f'elapsed: {elapsed_time}s\n'
63                      f'walltime: {end - start}s\n')
64         if ret != 0:
65             logger.info(f'Exit {ret}')
66         else:
67             logger.debug(f'Exit {ret}')
68         sys.exit(ret)
69     return initialize_wrapper