Last active
December 1, 2021 17:14
-
-
Save elmotec/6008118 to your computer and use it in GitHub Desktop.
Minimal python program with logging and argparse.
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 | |
| # encoding: utf-8 | |
| """Minimal python commad line.""" | |
| import sys | |
| import argparse | |
| import logging | |
| module = sys.modules['__main__'].__file__ | |
| log = logging.getLogger(module) | |
| def parse_command_line(argv): | |
| """Parse command line argument. See -h option | |
| :param argv: arguments on the command line must include caller file name. | |
| """ | |
| formatter_class = argparse.RawDescriptionHelpFormatter | |
| parser = argparse.ArgumentParser(description=module, | |
| formatter_class=formatter_class) | |
| parser.add_argument("--version", action="version", | |
| version="%(prog)s {}".format(__version__)) | |
| parser.add_argument("-v", "--verbose", dest="verbose_count", | |
| action="count", default=0, | |
| help="increases log verbosity for each occurence.") | |
| parser.add_argument('-o', metavar="output", | |
| type=argparse.FileType('w'), default=sys.stdout, | |
| help="redirect output to a file") | |
| #parser.add_argument('input', metavar="input", | |
| ## nargs='+', # argparse.REMAINDER, | |
| #help="input if any...") | |
| arguments = parser.parse_args(argv[1:]) | |
| # Sets log level to WARN going more verbose for each new -v. | |
| log.setLevel(max(3 - arguments.verbose_count, 0) * 10) | |
| return arguments | |
| def main(): | |
| """Main program. Sets up logging and do some work.""" | |
| logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, | |
| format='%(name)s (%(levelname)s): %(message)s')) | |
| try: | |
| arguments = parse_command_line(sys.argv) | |
| # Do something with arguments. | |
| finally: | |
| logging.shutdown() | |
| if __name__ == "__main__": | |
| sys.exit(main()) |
Author
The log is going to stderr. Only the output goes to the file referenced in -o. However, I use click nowadays for command line utilities. Much easier. I will probably delete that gist.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't seem to actually write the logs to a file when
-ois specified. It only creates the file.