Skip to content

Instantly share code, notes, and snippets.

@andreas-wilm
Created January 5, 2016 02:16
Show Gist options
  • Save andreas-wilm/b6031a84a33e652680d4 to your computer and use it in GitHub Desktop.
Save andreas-wilm/b6031a84a33e652680d4 to your computer and use it in GitHub Desktop.
Repeateable -v and -q for setting logging level with argparse (Python)
#!/usr/bin/env python
# Example for using repeateable -v and -q for setting logging level
# with argparse. works with python 2 and 3. based on
# https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/
#
# masklinn: """A trick I like is using repeatable -v and -q to select
# the logging level. The logging levels are actually integers with a
# 10 increment (DEBUG is 10, CRITICAL is 50). It's very easy with
# argparse's count action or click's count=True"""
#
# script -vv -> DEBUG
# script -v -> INFO
# script -> WARNING
# script -q -> ERROR
# script -qq -> CRITICAL
# script -qqq -> no logging at all
import argparse
import logging
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-v', '--verbose', action='count', default=0)
parser.add_argument('-q', '--quiet', action='count', default=0)
# ...
args = parser.parse_args()
logging_level = logging.WARN + 10*args.quiet - 10*args.verbose
logging.basicConfig(level=logging_level)
logger = logging.getLogger()
logger.debug("DEBUG")
logger.info("INFO")
logger.warn("WARN")
logger.error("ERROR")
logger.critical("CRITICAL")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment