i want filter screen print python program.
ideally, nice specify "print blacklist", such one.
*futurewarning* info*
when part of screen printout matches 1 of above patterns, whole printout filtered out.
i'm surprised no 1 has yet ask question, think extremely useful, because without it, need go through different types of screen printouts , deal them accordingly. can imagine of them may due print
, due warning
, etc.
i running python script bash, bash-based methods welcome too!
i want filter screen print python program.
you can use python's logging
module, routing print , warnings output through it:
# in main module import logging # -- log output myapp.log logging.basicconfig(filename='myapp.log', level=logging.debug) # -- or log output console logging.basicconfig(level=logging.debug) # route output logging logging.capturewarnings(true) print = logging.info
with add own filter
filter output per required keywords:
# define filter in own module, logfilter.py class outputfilter(logging.filter): def __init__(self, keywords, name=none): super(outputfilter, self).__init__(name) self.keywords = keywords def filter(self, record): msg = record.getmessage() return not any(k in msg k in self.keywords) # add in main module logfilter import outputfilter flt = outputfilter(['*futurewarning*', 'info*']) logger = logging.getlogger() # root logger logger.addfilter(flt) warnlogger = logging.getlogger('py.warnings') # warnings logger warnlogger.addfilter(flt)
(...) without it, need go through different types of screen printouts , deal them accordingly.
if can change source code better use module logger instead of print:
# in module output, right after imports logger = logging.getlogger(__name__) ... # instead of print logger.info(...) logger.error(...) logger.debug(...)
the advantage logging
allows fine grained control on output , where, while configuring central place.
for example, while above uses root logger applies logging output, every module of application can have own logger, specific configuration, e.g.
# somewhere in main module # -- basic config console logging.basicconfig(level=logging.debug) # -- module output should go own file logger = logging.getlogger('path.to.module.a') handler = logging.filehandler(filename='myapp-a.log') # see above logger.sethandler(handler) logger.setlevel(logging.info) # path/to/module/a.py # -- right @ top of module import logging logger = logging.getlogger(__name__) ... # in actual code logger.info('info message')
this example route info messages module file myapp-a.log
while other output goes terminal.
note: examples adopted python logging cookbook. check out tutorial more in-depth explanations.
Comments
Post a Comment