Skip to content

argumentParsing

holzkohlengrill edited this page Dec 15, 2023 · 2 revisions
#!/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 arguments
    args = parser.parse_args()
    print(args.verbose)            # access arguments by name


    # 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
Clone this wiki locally