H.T.
H.T.

Reputation: 11

How to implement nested optional arguments using python argparse

I am trying to come up with a tool to log-into my server: myLogin [-h] [--ip [Address]] [UserName] [Password]

  1. When --ip is not used, then tool will use an URL name (my.server.net) for connection.
  2. When --ip is used but no Address supplied, then tool will use default IP address (192.168.1.1) for connection.
  3. Address cannot be supplied without --ip switch.
  4. UserName and Password are optional and have built-in defaults.

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

Answers (1)

Wyrmwood
Wyrmwood

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

Related Questions