Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse add_argument alias

Is there a way to create an alias using argparse?

For example, I want to do something like this:

parser.add_argument('--foo' ...)
parser.add_argument_alias('--bar', '--foo')

That is, using --bar should be equivalent to using --foo.

like image 655
walkerlala Avatar asked Jun 17 '18 13:06

walkerlala


People also ask

What is parser Add_argument in Python?

parser. add_argument('indir', type=str, help='Input dir for videos') created a positional argument. For positional arguments to a Python function, the order matters. The first value passed from the command line becomes the first positional argument. The second value passed becomes the second positional argument.

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What does parse_args return?

parse_args() returns two values: options, an object containing values for all of your options— e.g. if "--file" takes a single string argument, then options. file will be the filename supplied by the user, or None if the user did not supply that option.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.


2 Answers

You can simply call:

parser.add_argument('--foo', '--bar', ...)

at least for Python 3.5.

This is how I tested it in ipython:

In [1]: import argparse

In [2]: parser = argparse.ArgumentParser()

In [3]: parser.add_argument('--foo', '--bar')
Out[3]: _StoreAction(option_strings=['--foo', '--bar'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)

In [4]: parser.parse_args(['--foo', 'FOO'])
Out[4]: Namespace(foo='FOO')

In [5]: parser.parse_args(['--bar', 'FOO'])
Out[5]: Namespace(foo='FOO')
like image 86
Jonathan Avatar answered Oct 05 '22 04:10

Jonathan


Not exactly what you asked for, but when you want to alias a key-value combination instead, as in --bar should be equivalent to using using --foo=baz, you can use the dest parameter:

parser.add_argument('--bar', dest='foo', action='store_const', const='baz')
like image 21
phil294 Avatar answered Oct 05 '22 04:10

phil294