Verbosity Check Style
mark_bottjer at hotmail.com
Fri Aug 13 01:47:51 CEST 2004
Dan Sommers wrote:
> On Thu, 12 Aug 2004 11:23:49 -0400, <brianc at temple.edu> wrote:
>>I would like to get people's views on the best way to implement
>>verbosity (or any command-line option) into python scripts.
> Use the logging module (new in 2.3). I think that verbosity equates to
> the INFO level.
Not always. Many programs have multiple levels of informative verbosity,
where each level exposes "more" information. Of course, the additional
information can be viewed as DEBUG, but there can be multiple levels of
Even if you want more than one level of verbosity, you can still use the
logging module (or any other facility, for that matter). I use a Verbose
class, which I pass an instance of to anything in my code which wants to
log something. A simplified version would be:
import sys as __sys
def __init__(self, verbosity = 0, log = __sys.stderr):
self.__vebosity = verbosity
self.__log = log
def __call__(self, verbosity, msg):
if verbosity >= self.__verbosity:
print >>self.__log, '*' * verbosity, msg
if __name__ == '__main__':
verbose = Verbose(4, sys.stdout)
verbose(1, "Level one message.")
verbose(3, "Level three message.")
verbose(5, "Level five message.")
Which gives the following output when imported:
* Level one message.
*** Level three message.
The nice thing here is that, once you've got it in a class, you can
subclass it. This allows you to add helper methods to make logging
certain types of information easier, or to support different types of
logger. You can even use it to switch at runtime between using the
logger module, dumping straight to a stream, or both.
I find it to be quite flexible.
More information about the Python-list