CentAu
CentAu

Reputation: 11190

argparse: How to allow multiple names for single argument?

Is it possible to use more than one name to refer to a single argument in argparse? Specifically, I want to allow user to specify an argument by either underscore and hyphen (dash)?

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input-file')
args = parser.parse_args()

For example, I want both of the following options to work for the argument args.input_file:

python main.py --input-file /tmp/file
python main.py --input_file /tmp/file

Upvotes: 7

Views: 4010

Answers (1)

norok2
norok2

Reputation: 26946

Simply listing more options in .add_argument():

arg_parser.add_argument('--input-file', '--input_file')

should do the trick.

Note that using a minus - character in your argument is the preferred GNU syntax.


Note that the names can be totally unrelated, e.g.:

arg_parser.add_argument('-bar', '--foo', '--input-file', '--input_file')

In this case, the first value starting with -- (normalized) is used in the arguments namespace:

args = arg_parser.parse_args()
print(args)
# Namespace(foo=...)

Upvotes: 13

Related Questions