1

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.

2
  • 1
    Try nargs='?' with default` and const parameters. Commented Aug 16, 2017 at 17:56
  • @hpaulj, Thank you Commented Aug 16, 2017 at 18:26

1 Answer 1

2
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')
>>>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.