0

I have two arguments: --1st and --2nd I'm trying to make "-2nd" argument required only if "1st" argument set.

For example:

If "1st" is set and "2nd" is set - good

If "1st" is not set and "2nd" is not set - good

Other cases are bad. Help me, please

GolovDanil
  • 133
  • 2
  • 11
  • Are both arguments optional? or is only the second optional? – Headhunter Xamd Oct 28 '16 at 11:53
  • Both optional. But if 1st set, 2nd is required. If 2nn set, first is required. In other cases there must be an error – GolovDanil Oct 28 '16 at 12:09
  • I would make them both optional in argparse, then write my own code for validation checks on the results of calling `parse_args`. – larsks Oct 28 '16 at 12:30
  • Sounds like both are always required? If so, just use a single argument which consumes two values. – languitar Oct 28 '16 at 13:03
  • 1
    This is a duplicate of: http://stackoverflow.com/questions/21879657/argparse-argument-dependency – kabanus Oct 28 '16 at 13:12
  • Probably a duplicate. Not going to close with the dupehammer just because the accepted answer there is mine. Anyway: I concur with myself from 2014: just use a single argument that eventually takes two values using `nargs=2`... much easier then having two distinct options that are actually just a single option. – Bakuriu Oct 28 '16 at 14:52
  • There is a prioblem, I can't use single option. It's my task to use two distinct options. Also I mast use argparse. – GolovDanil Oct 28 '16 at 18:04

1 Answers1

3

I like Kabanus' solution. Here is another one, which is simpler for new user:

parser = argparse.ArgumentParser()
parser.add_argument('--first')
parser.add_argument('--second')
options = parser.parse_args()

# Error checking
if (options.first is None) != (options.second is None):
    print 'Error: --first and --second must both be supplied or omitted'

Discussion

  • I don't use --1st and --2nd since options.1st does not work and getattr(options, '1st') is too messy. Instead, I use--firstand--second` for illustration purpose.
  • The expression (options.first is None) != (options.second is None) expressed your error condition succinctly.
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • You could still use `--1st` as the command line name if you provided a `dest='first'` for a useful Python attribute name. – ShadowRanger Nov 01 '16 at 03:59
  • `parser.error('--first and --second must both be supplied or omitted')` for a more consistent error message – antak Feb 07 '20 at 04:31