simple.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
import sys
from logging import getLogger, StreamHandler, Formatter
logger = getLogger(__name__)
def global_loginit(logname=__name__, format="%(message)s", stream=sys.stderr, level=20, datefmt="%Y-%m-%dT%H:%M:%S" ):
_logger = getLogger(logname)
_logger.setLevel(level)
_handle = StreamHandler(stream)
_handle.setFormatter(Formatter(fmt=format,datefmt=datefmt))
_logger.addHandler(_handle)
return _logger
def main(opts):
logger.info("Python {0}".format(sys.version))
logger.warning("{0}".format(opts))
logger.info("{0}".format(opts))
logger.debug("{0}".format(opts))
opts["consolelogger"].info("This is it")
def options(opt, add_func, help_tail):
optadd=add_func(opt)
optadd('-P', '--prof', default=False, action='store_true', help='get profile' + help_tail )
optadd('-D', '--Debug', default=False, action='store_true', help='log debug' + help_tail)
optadd('-Q', '--Quiet', default=False, action='store_true', help='log quiet' + help_tail)
if type(opt).__name__.startswith("Arg"):
optadd("args", type=str, nargs='*')
return opt
def parsed_opts():
try:
import argparse
description= "test"
epilog = """epilog
"""
opt = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=description, epilog=epilog)
add_func = lambda x: x.add_argument
parsefunc = lambda x: dict(vars(x))
help_tail=''
except ImportError as e:
import optparse
opt = optparse.OptionParser()
add_func = lambda x: x.add_option
parsefunc = lambda x: dict(vars(x[0]).items() + [('args', x[1])])
help_tail=' [default: %default]'
return parsefunc( options(opt, add_func, help_tail).parse_args())
if __name__ == '__main__':
opts = parsed_opts()
loggercfg = {
"format": "%(asctime)s.%(msecs).03d %(process)d %(module).4s %(levelname).4s %(lineno)d/%(funcName)s %(message)s",
"level": 20 if (not opts["Debug"] and not opts["Quiet"]) else 10 if opts["Debug"] else 30
}
global_loginit(**loggercfg)
opts["consolelogger"] = global_loginit(logname=__name__+"console",stream=sys.stdout)
if opts['prof']:
import cProfile
cProfile.run('main(opts)')
sys.exit(0)
main(opts)
Recommended Posts