Search code examples
pythoncommand-linegetopt

Getopt not reading all options


this is my first time using Getopt in python and I came across a problem:

opts, args = getopt.getopt(sys.argv[1:], "hrs", ["help","random","somethingelse"])

for o, a in opts:
    if o in "-h" or "--help":
        help()
    elif o in "-r" or "--random":
        random()
    elif o in "-s" or "--somethingelse":
        somethingelse()  

If I were to type: python test.py -r or python test.py -s. It would still go to the help function instead of going to the random() or somethingelse() function.


Solution

  • You need to put the possible options in lists or tuples:

    opts, args = getopt.getopt(sys.argv[1:], "hrs", ["help","random","somethingelse"])
    
    for o, a in opts:
        if o in ["-h", "--help"]:
            help()
        elif o in ["-r", "--random"]:
            random()
        elif o in ["-s", "--somethingelse"]:
            somethingelse()
    

    The way you currently have it, your first condition if o in "-h" or "--help": is perfectly valid Python, but it will always be True, because what you are actually testing is the "truthiness" of o in "-h" and "--help" respectively. This is always True because even if o in "-h" is False, "--help" is always True since it is a non-empty string.

    On the other hand, if you test if o in ["-h", "--help"]:, this will check if o is one of the items in the list ["-h", "--help"], and will only return True if it is.