0

hi i want to add the following arguments:

parser = argparse.ArgumentParser()
parser.add_argument('-n','--name', required=True)
parser.add_argument("-sd", "--start_date", dest="start_date", 
                        type=valid_date,
                        help="Date in the format yyyy-mm-dd")
parser.add_argument("-ed", "--end_date", dest="end_date", 
                        type=valid_date,
                        help="Date in the format yyyy-mm-dd")

i want that in case the name='test1' then start_date and end_date will be mandatory. can it be done with arparse? or do i need some validation method to enforce it to be mandatory?

thanks

4
  • 1
    You cannot make some args depending on other, you have to do it in the code later Commented May 31, 2020 at 15:49
  • I think this answers your question: stackoverflow.com/questions/25626109/… Commented May 31, 2020 at 15:50
  • Does this answer your question? Argparse: Required argument 'y' if 'x' is present Commented May 31, 2020 at 15:51
  • 2
    @Aziz and БогданТуренко Please notice that this question is not about presence of an argument, but a specific value it gets Commented May 31, 2020 at 15:52

1 Answer 1

3

You can check the condition and then check if the other arguments are both provided.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-n','--name', required=True)
parser.add_argument("-sd", "--start_date", dest="start_date", 
                        help="Date in the format yyyy-mm-dd")
parser.add_argument("-ed", "--end_date", dest="end_date", 
                        help="Date in the format yyyy-mm-dd")

args = parser.parse_args()

if args.name == "test1":
    if args.start_date is None or args.end_date is None:
        parser.error('Requiring start and end date if test1 is provided')
Sign up to request clarification or add additional context in comments.

1 Comment

although i was looking to avoid using "if", i see there is no other way :)

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.