0

I am trying to make the parameter -i required only if the parameter -r isn't present. This is what I have at the moment:

 parser.add_argument(
        '-i', '--input-location',
        help='Input location',
        required=True,
        dest='input_location'
    )

 parser.add_argument(
        '-r','--report',
        help='Show data report ',
        required=False,
        default=False,
        action='store_true'
    )

So in nearly all cases -i will be required as a parameter:

python program.py -i /input_location

But if -r parameter is used then the -i parameter won't be needed:

python program.py -r
3
  • Your question has already been answered here: stackoverflow.com/questions/18025646/… Commented Feb 17, 2016 at 10:43
  • It would also help, even if just for later readers, to specify what argument parser you are using. Optparse, argparse etc Commented Feb 17, 2016 at 10:54
  • Apologies I am using argparse Commented Feb 17, 2016 at 10:57

2 Answers 2

1

You can check the result of the option parser afterward and signal an error when neither of report or input_location were filled.

Here is my solution:

from optparse import OptionParser
import sys

parser = OptionParser()


parser.add_option(
        '-i', '--input-location',
        help='Input location',
        default=False,
        dest='input_location'
    )

parser.add_option(
        '-r','--report',
        help='Show data report ',

        default=False,
        action='store_true'
    )



(options, args) = parser.parse_args()

print options, args

if options.report == False and options.input_location == False:
    print "Error: You need to specfify at least -i or -r parameter."
    sys.exit(1)
Sign up to request clarification or add additional context in comments.

Comments

1

It sounds like your program is performing two distinct actions depending on which option you provide to the program. This does not directly answer your question but, perhaps in your case you could avail of the mutual exclusion feature

Within the linked text, it states:

The add_mutually_exclusive_group() method also accepts a required argument, to indicate that at least one of the mutually exclusive arguments is required

This would force the user to use either -i or -r.

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.