Skip to content

Instantly share code, notes, and snippets.

@stg7
Created August 29, 2017 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stg7/1e4710f9a5ea788ca1109f352ef02954 to your computer and use it in GitHub Desktop.
Save stg7/1e4710f9a5ea788ca1109f352ef02954 to your computer and use it in GitHub Desktop.
argument parsing with python3
#!/usr/bin/env python3
import sys
import argparse
def main(args):
""" Example for command line argument parsing using argparse,
if you ever need to program java you can use: [argparse4j](https://argparse4j.github.io/)
"""
parser = argparse.ArgumentParser(description='DESC', epilog="stg7 2016", formatter_class=argparse.ArgumentDefaultsHelpFormatter) # see also here for other options: https://docs.python.org/3/library/argparse.html#argumentparser-objects
# some examples for possible arguments, optional parameters as long as there is a default value
parser.add_argument('--intpara', type=int, default=42, help='integer parameter')
parser.add_argument('--xy', type=str, default="hello", help='xy', required=True) # argument is required
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") # short and long versions
# -h and --help is always there
# flag example
parser.add_argument('-f', dest='flag', action='store_true', help='a flag')
# multiple required arguments (without nargs="+" you have exactly one req. argument)
parser.add_argument('infile', nargs="+", type=str, help='multiple input files')
# parse defined arguments
argsdict = vars(parser.parse_args())
# there is still more possible with argparse,
# e.g. subparser, see [argparse tutorial](https://docs.python.org/3/howto/argparse.html)
print(argsdict)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:])) # return an exit code and call main with parameters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment