Skip to content

Instantly share code, notes, and snippets.

@AntoniosHadji

AntoniosHadji/cli.py

Created Feb 20, 2019
Embed
What would you like to do?
python cli option parser with logging
#!/usr/bin/env python3
import argparse
import logging
import os
import pathlib
import sys
from datetime import date, timedelta
# create logger
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
pathlib.Path(os.environ['HOME'] + '/logs').mkdir(parents=False, exist_ok=True)
fh = logging.FileHandler(os.environ['HOME'] + '/logs/' + __name__ + '.log')
fh.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
formatter.default_msec_format = '%s.%03d'
# add formatter to ch
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add ch to logger
log.addHandler(ch)
log.addHandler(fh)
# 'application' code
# logger.debug('debug message')
# logger.info('info message')
# logger.warn('warn message')
# logger.error('error message')
# logger.critical('critical message')
log.debug(sys.argv)
yesterday = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d")
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--date', default=yesterday)
parser.add_argument('--priority', default='P1')
parser.add_argument('--prod', action='store_true')
args = parser.parse_args()
log.debug(os.path.expanduser('~'))
log.debug(os.environ['HOME'])
log.debug(str(args))
log.debug("Date is set to: {}".format(args.date))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment