Search code examples
pythonsysgetopts

python getopts option not matching on operator '=='


following some examples from https://www.programcreek.com/python/example/121/getopt.getopt where they make option comparisons with == i.e (option == "--json"), I am trying to enter the if statement. However option will not match despite being of type string and "--json". Can anyone see what is going wrong?


import sys, getopt

argv = sys.argv[1:]
def main(argv): 
    try:
        opts, args = getopt.getopt(argv,'',['json ='])
    except:
        print("failed to get arguments")
    for (option, value) in opts:
        print(option)
        print(type(option))
        if str(option) == "--json":
            print ("enters here")

main(argv)

$ python test.py --json data

--json

<class 'str'>


Solution

  • You are using the longopts parameter incorrectly. Using an = in the option indicates that the option takes arguments but you are not passing your data argument to the --json option, you are passing it to the script as a global argument (because you omitted the = from the --json option).

    Note also that you must remove the whitespace between the option and its argument. Finally, you should never use a bare except.

    def main(argv):
        try:
            opts, args = getopt.getopt(argv, "", ["json="])
            print(opts)
        except Exception:
            print("failed to get arguments")
    
        for (option, value) in opts:
            print(option)
            print(type(option))
            if str(option) == "--json":
                print("enters here")
    

    Usage:

    $ python test.py --json='{"firstName":"John", "lastName":"Doe"}'  
    [('--json', '{firstName:John, lastName:Doe}')]
    --json       
    <class 'str'>
    enters here