Random changes.
[python_utils.git] / bootstrap.py
1 #!/usr/bin/env python3
2
3 import functools
4 import logging
5 import os
6 import pdb
7 import sys
8 import traceback
9
10 # This module is commonly used by others in here and should avoid
11 # taking any unnecessary dependencies back on them.
12
13 from argparse_utils import ActionNoYes
14 import config
15
16
17 logger = logging.getLogger(__name__)
18
19 args = config.add_commandline_args(
20     f'Bootstrap ({__file__})',
21     'Args related to python program bootstrapper and Swiss army knife')
22 args.add_argument(
23     '--debug_unhandled_exceptions',
24     action=ActionNoYes,
25     default=False,
26     help='Break into pdb on top level unhandled exceptions.'
27 )
28
29
30 def handle_uncaught_exception(
31         exc_type,
32         exc_value,
33         exc_traceback):
34     if issubclass(exc_type, KeyboardInterrupt):
35         sys.__excepthook__(exc_type, exc_value, exc_traceback)
36         return
37     logger.exception(f'Unhandled top level {exc_type}',
38                      exc_info=(exc_type, exc_value, exc_traceback))
39     traceback.print_exception(exc_type, exc_value, exc_traceback)
40     if config.config['debug_unhandled_exceptions']:
41         logger.info("Invoking the debugger...")
42         pdb.pm()
43
44
45 def initialize(entry_point):
46
47     """Remember to initialize config and logging before running main."""
48     @functools.wraps(entry_point)
49     def initialize_wrapper(*args, **kwargs):
50         sys.excepthook = handle_uncaught_exception
51         config.parse(entry_point.__globals__['__file__'])
52
53         import logging_utils
54         logging_utils.initialize_logging(logging.getLogger())
55
56         config.late_logging()
57
58         logger.debug(f'Starting {entry_point.__name__} (program entry point)')
59
60         ret = None
61         import timer
62         with timer.Timer() as t:
63             ret = entry_point(*args, **kwargs)
64         logger.debug(
65             f'{entry_point.__name__} (program entry point) returned {ret}.'
66         )
67
68         walltime = t()
69         (utime, stime, cutime, cstime, elapsed_time) = os.times()
70         logger.debug(f'\n'
71                      f'user: {utime}s\n'
72                      f'system: {stime}s\n'
73                      f'child user: {cutime}s\n'
74                      f'child system: {cstime}s\n'
75                      f'elapsed: {elapsed_time}s\n'
76                      f'walltime: {walltime}s\n')
77         if ret != 0:
78             logger.info(f'Exit {ret}')
79         else:
80             logger.debug(f'Exit {ret}')
81         sys.exit(ret)
82     return initialize_wrapper