Last active
July 14, 2022 04:44
-
-
Save leoncvlt/ce1d0fa391b3d60e0e9ba93d94560aeb to your computer and use it in GitHub Desktop.
Boilerplate for a simple python script with arguments parsing and coloured logging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys, argparse, logging | |
log = logging.getLogger(__name__) | |
def main(): | |
# set up argument parser | |
parser = argparse.ArgumentParser(description='A simple python script') | |
parser.add_argument('target', help='positional argument') | |
parser.add_argument("-s", "--string", help="An optional string argument") | |
parser.add_argument("-b", "--bool", action="store_true", default=False, help='An optional boolean argument') | |
parser.add_argument("-l", "--list", choices={"apple", "orange"}, default="apple", help="An optional list argument") | |
parser.add_argument("-v", "--verbose", action="store_true", help="Increases output verbosity") | |
args = parser.parse_args() | |
# set up logger | |
log.setLevel(logging.INFO if not args.verbose else logging.DEBUG) | |
log_screen_handler = logging.StreamHandler(stream=sys.stdout) | |
log.addHandler(log_screen_handler) | |
log.propagate = False | |
# add colored logs if colorama is availabe | |
try: | |
import colorama, copy | |
LOG_COLORS = { | |
logging.DEBUG: colorama.Fore.GREEN, | |
logging.INFO: colorama.Fore.BLUE, | |
logging.WARNING: colorama.Fore.YELLOW, | |
logging.ERROR: colorama.Fore.RED, | |
logging.CRITICAL: colorama.Back.RED | |
} | |
class ColorFormatter(logging.Formatter): | |
def format(self, record, *args, **kwargs): | |
# if the corresponding logger has children, they may receive modified | |
# record, so we want to keep it intact | |
new_record = copy.copy(record) | |
if new_record.levelno in LOG_COLORS: | |
new_record.levelname = "{color_begin}{level}{color_end}".format( | |
level=new_record.levelname, | |
color_begin=LOG_COLORS[new_record.levelno], | |
color_end=colorama.Style.RESET_ALL, | |
) | |
return super(ColorFormatter, self).format(new_record, *args, **kwargs) | |
log_screen_handler.setFormatter(ColorFormatter(fmt='%(asctime)s %(levelname)-8s %(message)s', | |
datefmt="{color_begin}[%H:%M:%S]{color_end}".format( | |
color_begin=colorama.Style.DIM, | |
color_end=colorama.Style.RESET_ALL | |
))) | |
except ModuleNotFoundError as identifier: | |
pass | |
# run the script | |
log.info(f"Script called with the following arguments: {vars(args)}") | |
if __name__ == '__main__': | |
try: | |
main() | |
except KeyboardInterrupt: | |
log.critical('Interrupted by user') | |
try: | |
sys.exit(0) | |
except SystemExit: | |
os._exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment