argparse: How to allow multiple names for single argument?

Viewed 1628

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
1 Answers

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.

Related