#!/usr/bin/env python3 """Simple program to demonstrate the most common features of Python's standard "argparse" library. """ import argparse import os from pprint import pprint as pprint import sys __version__ = "1.0.0" def main(): # Create a new ArgrumentParser instance that shows the default # values for options that have them as part of the help message. parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Sample program to demonstrate the \"argparse\" library.") # Demonstrate an optional flag (i.e., just a boolean, no parameter). parser.add_argument("-n", "--dry-run", action="store_true", dest="dry_run", help="dry run") # Parse a string argument. parser.add_argument("--host", required=True, dest="host", help="remote host") # Parse a flag. parser.add_argument("--listen", dest="listen", action="store_true", help="listen for connections") # Parse an integer argument that has a default value. parser.add_argument("--port", type=int, required=False, default=8080, dest="port", help="port") # Print the version. This has to be handled with a special # action; otherwise, the user also would have to provide all the # required options above just to print out the version. parser.add_argument("-v", "--version", action="version", version="%s %s" % (os.path.basename(sys.argv[0]), __version__), help="version infomation") # Everything else on the command-line is a file name. parser.add_argument(dest="fnames", metavar="file", nargs="*") # Parse command-line arguments. args = parser.parse_args() pprint(args) if __name__ == "__main__": main()