Created
August 29, 2017 08:51
-
-
Save stg7/1e4710f9a5ea788ca1109f352ef02954 to your computer and use it in GitHub Desktop.
argument parsing with python3
This file contains 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 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