0

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'>

Terk
  • 25
  • 6
  • 1
    Just a heads up, you should never use a [bare except](https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except). – ddejohn Jun 16 '22 at 18:07
  • 2
    I'd suggest just use argparse https://docs.python.org/3/library/argparse.html#prog – Anentropic Jun 16 '22 at 18:19

1 Answers1

1

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  
ddejohn
  • 8,775
  • 3
  • 17
  • 30