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
.
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.
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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.
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.
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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With