argumentparser ignore second character in space

56 Views Asked by At

I have the below code

 parser = argparse.ArgumentParser(description = 'Generates calculations from input files')
 parser.add_argument('-c', '--by-client', action = 'store_true', help = 'Output issues broken down by client')
 parser.add_argument('-cn', '--client-name',  help = 'Generate output by client name provided', default=None)

When I am running the script and giving option like -cn it's throwing an error

error: argument -c/--by-client: ignored explicit argument 'n'

Strangely it was working before, but at sudden it stopped working.

1

There are 1 best solutions below

4
user1129682 On

Using a single - denotes a flag which is only single character. Your -cn will always be interpreted as two flags -c and -n.

The Python manual actually doesn't state this, at the time of this writing. This is the behaviour of getopt and a POSIX standard, as it would seem.

From what I believe is the standard document

Guideline 3: Each option name should be a single alphanumeric character (the alnum character classification) from the portable character set. The -W (capital-W) option shall be reserved for vendor options. Multi-digit options should not be allowed.

Guideline 4: All options should be preceded by the '-' delimiter character.

Apparently, when using a single hyphen -, we call the parameter an option and they are always single character. When using double hypen -- we call the parameter and argument and they can have longer names.


Edit 1:

Argparse does not use getopt and I wasn't able to find any claim that argparse wants to work like getopt. It just happens to work like getopt.


Edit 2: It would seem argparse let's you specify short options with more than one character but then only uses the first character.

import argparse
x = argparse.ArgumentParser()
x.add_argument('-fo', action='store', dest='fstore')

y = x.parse_args(['-f', 'foo'])

print(y)

does actually print Namespace(fstore='foo') on Python 3.11.2. It appears argparse is a bit overly tollerant when defining options.