Reputation: 11
I am trying to come up with a tool to log-into my server: myLogin [-h] [--ip [Address]] [UserName] [Password]
How do I achieve nested optional arguments with dependency: [--ip [Address]] using python argparse library?
I tried using add_subparsers and add_argument_group without any luck.
Upvotes: 1
Views: 474
Reputation: 3589
nargs='?'
nargs can be set to ?
'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this:
In your case, you are using an optional argument so the the value from const will be used when address is not supplied. If the argument is missing entirely, then the value from default is used. For example,
>>> from argparse import ArgumentParser
>>> parser = ArgumentParser()
>>> parser.add_argument('--ip', nargs='?', default='my.server.net', const='192.168.1.1')
_StoreAction(option_strings=['--ip'], dest='ip', nargs='?', const='192.168.1.1', default='my.server.net', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args([])
Namespace(ip='my.server.net')
>>> parser.parse_args(['--ip'])
Namespace(ip='192.168.1.1')
>>> parser.parse_args(['--ip', '1.2.3.4'])
Namespace(ip='1.2.3.4')
>>>
Upvotes: 2