Last active
February 9, 2016 15:55
-
-
Save SpotlightKid/7a3162f8180bcf04dcbd to your computer and use it in GitHub Desktop.
Logging in Python command line scripts
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 argparse | |
| import logging | |
| import sys | |
| log = logging.getLogger(__name__) | |
| def main(args=None): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('-v', '--verbose', action="store_true", | |
| help="Log debugging info to standard error output.") | |
| args = parser.parse_args(sys.argv[1:] if args is None else args) | |
| logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, | |
| format="%(levelname)s: %(message)s") | |
| # Your script here... | |
| log.info("Message at normal verbosity") | |
| log.debug("Message at enhanced verbosity (with -v command line switch)") | |
| return 0 | |
| if __name__ == '__main__': | |
| sys.exit(main(sys.argv[1:]) or 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment