Skip to content

Instantly share code, notes, and snippets.

@Drunkar Drunkar/CLI_template.py
Last active Oct 19, 2018

Embed
What would you like to do?
# coding: utf-8
import logging
import traceback
import argparse
import time
from contextlib import contextmanager
logger = logging.getLogger(__name__)
@contextmanager
def time_logger(label):
start = time.time()
yield
end = time.time()
logger.info("{}: {:.3f} sec consumed.".format(label, end - start))
def main(args):
try:
with time_logger("1.first_process"):
print("Hello, world!")
except Exception as e:
logger.error(str(e) + ":" + traceback.format_exc())
if __name__ == '__main__':
# args
parser = argparse.ArgumentParser(
description="Awesome CLI.")
parser.add_argument(
"-d", "--debug", action="store_true", help="Debug mode.")
args = parser.parse_args()
# logger
if args.debug:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.INFO
formatter = logging.Formatter(
fmt="[%(asctime)s] %(levelname)s [%(name)s/%(funcName)s() at line %(lineno)d]: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
logger.setLevel(LOG_LEVEL)
# stdout
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
stream_handler.setLevel(LOG_LEVEL)
logger.addHandler(stream_handler)
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.