0

Using argparse, I'd like to be able to have two separate but co-requisite (and otherwise optional) options.

This is similar to Python argparse: Require two corequisite positional arguments, however the solution suggested there doesn't work for me because I want the options to be separate and named.

I want the usage to look a bit like this:

foo.py [-h] [--username USER --password PASS] OTHER_ARGS

I want the user to be able to either provide both the --username and --password options, or neither, but to receive an error if they only pass one.

PeterJCLaw
  • 1,862
  • 1
  • 16
  • 20
  • While your suggestion is clearer, an alternative is to use one option that requires two arguments (user and pass), e.g. `--login USERNAME PASSWORD`. – 9769953 Mar 10 '20 at 21:25
  • 1
    Or, simply process after parsing. e.g `if (args.user and not args.pass) or (args.pass and not args.user):` – Tomerikoo Mar 10 '20 at 21:27
  • 1
    What @Tomerikoo says is correct, but for a more concise code, you can do `if bool(args.user) != bool(args.pass):` – blhsing Mar 10 '20 at 21:32

0 Answers0