user977828
user977828

Reputation: 7679

argparse combine with optional parameter

If the user use the optional parameter -o then the user has to use parameter -b as well. However, the -b parameter you have to use only if the user set the parameter -o.

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', nargs='?', required=True)
    parser.add_argument('-o', nargs='?', required=False)
    parser.add_argument('-b', nargs='?', required=????)

    args = parser.parse_args()

How is it possible to solve this problem?

Upvotes: 2

Views: 523

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226694

Add a test after args = parser.parse_args():

if args.o and not args.b:
   print >> sys.stderr, 'The -b option is required whenever -o is specified'
   sys.exit(1)

Upvotes: 2

Related Questions