Last active
October 22, 2018 08:23
-
-
Save aminamid/67fcb2212e437b5ba1e2 to your computer and use it in GitHub Desktop.
ぼくのかんがえたpython2.6こまんどらいんあぷりひながた ref: https://qiita.com/aminamid/items/99eb7ec1c71809ebee92
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import sys | |
import datetime | |
import itertools | |
def concat( ll ): | |
return list(itertools.chain(*ll)) | |
def nowstr(fmt="%Y-%m-%dT%H:%M:%S"): | |
return datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") | |
## logging | |
def change_state(obj, method_arglist_tpls): | |
for m_as in method_arglist_tpls: | |
getattr(obj, m_as[0])(*m_as[1]) | |
return obj | |
from logging import getLogger, StreamHandler, Formatter | |
def loginit(logname, format="%(message)s", stream=sys.stderr, level=15, datefmt="%Y/%m/%dT%H:%M:%S" ): | |
return change_state(getLogger(logname), [ | |
("setLevel", [level]), | |
("addHandler", [change_state( | |
StreamHandler(stream),[("setFormatter", [Formatter(fmt=format,datefmt=datefmt)])] | |
)]) | |
]) | |
## logging functions | |
import functools | |
def traclog(logger): | |
def recvfunc(f): | |
@functools.wraps(f) | |
def trac(*args, **kwargs): | |
logger.log(5,"ENTER:{0} {1}".format( f.__name__, kwargs if kwargs else args)) | |
result = f(*args, **kwargs) | |
logger.log(5,"RETRN:{0} {1}".format( f.__name__, result)) | |
return result | |
return trac | |
return recvfunc |
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
#!/usr/bin/env python [43/1901] | |
# -*- coding: utf-8 -*- | |
from signal import signal, SIGPIPE, SIG_DFL, SIGINT, SIG_IGN | |
signal(SIGPIPE,SIG_DFL) | |
import sys | |
import common | |
loggercfg = { | |
"format": "%(asctime)s.%(msecs).03d %(process)d %(thread)x %(levelname).4s;%(module)s(%(lineno)d/%(funcName)s) %(message)s", | |
"level": 15, | |
} | |
logstdcfg = { | |
"stream": sys.stdout, | |
"level": 15, | |
} | |
logger = common.loginit(__name__,**loggercfg) | |
logstd = common.loginit("std",**logstdcfg) | |
@common.traclog(logger) | |
def main(opts): | |
for l in sys.stdin: | |
if [f for f in opts["args"] if f in l ]: logger.info(l.strip()) | |
def parsed_opts(): | |
import optparse | |
opt = optparse.OptionParser() | |
opt.add_option("-P", "--prof", default=False, action="store_true", help="get profile [default: %default]" ) | |
opt.add_option("-L", "--loglevel", default=15, type="int", help="15: info, 10: debug, 5: trace [default: %default]" ) | |
(opts, args)= opt.parse_args() | |
return dict(vars(opts).items() + [("args", args)]) | |
if __name__ == '__main__': | |
opts = parsed_opts() | |
logger.setLevel(opts['loglevel']) | |
if opts['prof']: | |
import cProfile | |
cProfile.run('main(opts)') | |
sys.exit(0) | |
main(opts) |
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
#!/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 | |
def setM(obj, l): | |
for m in l: | |
getattr(obj, m[0])(*m[1]) | |
return obj | |
def loginit(logname, format="%(message)s", stream=sys.stderr, level=15, datefmt="%Y/%m/%dT%H:%M:%S" ): | |
return setM(getLogger(logname), [ | |
("setLevel", [level]), | |
("addHandler", [setM(StreamHandler(stream),[("setFormatter", [Formatter(fmt=format,datefmt=datefmt)])])]) | |
]) | |
loggercfg = { | |
"format": "%(asctime)s.%(msecs).03d %(process)d %(thread)x %(levelname).4s;%(module)s(%(lineno)d/%(funcName)s) %(message)s", | |
"level": 10, | |
} | |
logstdcfg = { | |
"level": 10, | |
"stream": sys.stdout, | |
} | |
logger = loginit(__name__,**loggercfg) | |
logstd = loginit("std",**logstdcfg) | |
def main(opts): | |
if opts['verbose']: logger.info("{0}".format(opts)) | |
for l in sys.stdin: | |
if [f for f in opts["args"] if f in l ]: logger.info(l.strip()) | |
def parsed_opts(): | |
import optparse | |
import os | |
opt = optparse.OptionParser() | |
opt.add_option("-p", "--prof", default=False, action="store_true", help="get profile [default: %default]" ) | |
opt.add_option("-v", "--verbose", default=False, action="store_true", help="show detail info [default: %default]" ) | |
(opts, args)= opt.parse_args() | |
return dict(vars(opts).items() + [("args", args)]) | |
if __name__ == '__main__': | |
opts = parsed_opts() | |
if opts['prof']: | |
import cProfile | |
cProfile.run('main(opts)') | |
sys.exit(0) | |
main(opts) |
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
#from logging import getLogger, basicConfig | |
# | |
#logger = getLogger(__name__) | |
#logcfg = { | |
# "format": "%(asctime)s.%(msecs).03d %(process)d %(thread)x %(levelname).4s;%(module)s(%(lineno)d/%(funcName)s) %(message)s", | |
# #"format": "%(message)s", | |
# "datefmt": "%Y/%m/%dT%H:%M:%S", | |
# "level": 10, | |
# "stream": sys.stdout, | |
#} | |
#basicConfig(**logcfg) | |
from logging import getLogger, basicConfig, StreamHandler, Formatter | |
def setM(obj, l): | |
for m in l: | |
getattr(obj, m[0])(*m[1]) | |
return obj | |
def loginit(logname, format,level,datefmt,stream ): | |
return setM(getLogger(logname), [ | |
("setLevel", [level]), | |
("addHandler", [setM(StreamHandler(stream),[("setFormatter", [Formatter(fmt=format,datefmt=datefmt)])])]) | |
]) | |
logger = loginit(__name__,"%(asctime)s.%(msecs).03d %(process)d %(thread)x %(levelname).4s;%(module)s(%(lineno)d/%(funcName)s) %(message)s",10,"%Y/%m/%dT%H:%M:%S",sys.stderr) | |
logstd = loginit("std","%(message)s",10,"%Y/%m/%dT%H:%M:%S",sys.stdout) |
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
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment