pythongetoptgetopts

python Getopt- different behavior when I pass arguments using single-character command-line flags & equivalent longer command-line flags


Code:

import getopt
import sys

print("Let's read the arguments from command line")

user_inputs = sys.argv[1:]
print(user_inputs)

# get option and value pair from getopt
try:
    opts, args = getopt.getopt(user_inputs, "fh:", ["findings=", "help"])
    #lets's check out how getopt parse the arguments
    print(opts)
    print(args)
except getopt.GetoptError:
    print('pass the arguments like -f <findings JSON file> -h <help> or --findings <findings JSON file> and --help <help>')
    sys.exit(2)

for opt, arg in opts:
    if opt in ("-h", "--help"):
        print('pass the arguments like -f <findings JSON file> -h <help> or --findings <findings JSON file> and --help <help>')
        sys.exit()
    elif opt in ("-f", "--findings"):
        # do something with the input file
    else:
        print('pass the arguments like -f <findings JSON file> -h <help> or --findings <findings JSON file> and --help <help>')
        sys.exit()

I get different behavior for opts, args = getopt.getopt(user_inputs, "fh:", ["findings=", "help"])

When I run with single-character command-line flags

% python3 py_args_options.py -f 'findings.json'
Let's read the arguments from command line
['-f', 'findings.json']
[('-f', '')]
['findings.json']

We can see opts has the value [('-f', '')] and args has the value ['findings.json']

However, when I run with equivalent longer command-line flags

python3 py_args_options.py --findings 'findings.json'
Let's read the arguments from command line
['--findings', 'findings.json']
[('--findings', 'findings.json')]
[]

We can see opts has the value [('--findings', 'findings.json')] and args is empty []

How can I fix this issue?


Solution

  • With the getopt() function the shortopts parameter needs a : to indicate an option which has a following argument.

    Just change your call to this:

    opts, args = getopt.getopt(user_inputs, "f:h", ["findings=", "help"])