Search code examples
pythonpython-3.xgetopt

Find multiple arguments in getopt command Python 3


I need the script to look into the arguments given in command line and give an error output if two specific arguments are given in the same command line.

Please note that parameters b & c are mutually exclusive.

I need to have a way that if in the command line both -b & -c is given, the system will provide an error message and exit. Also if there any other way to write the code?

Thanks, NH

My sample code is like this:

import getopt

def main():
    x = ''

    try:
            opts, args = getopt.getopt(sys.argv[1:], "habc",["help","Task_a", "Task_b", "Task_c"])
    except getopt.GetoptError:
            print("Wrong Parameter")
            sys.exit()
    for opt, args in opts:
        if opt in ("-h", "--help"):
            x = "h"

        elif opt in ("-a", "--Task_a"):
            x= "a"

        elif opt in ("-b", "--Task_b"):
            x = "b"

        elif opt in ("-c", "--Task_c"):
            x = "c"

        else:
            x = "something Else"

    return x 
if __name__ =="main":
    main()
print(main())

Solution

  • First of all, you should use argparse module that support mutual exclusion.

    To answer your question, you could use this simple logic

    optnames = [opt[0] for opt in opts]
    if (("-b" in optnames or "--Task-b" in optnames) and
            ("-c" in optnames or "--Task-c" in optnames)):
        print("-b and -c are mutually exclusive", file=sys.stderr)
        sys.exit()