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

mikeP
  • 81
  • 1
  • 7
  • 1
    You cannot make some args depending on other, you have to do it in the code later – azro May 31 '20 at 15:49
  • I think this answers your question: https://stackoverflow.com/questions/25626109/python-argparse-conditionally-required-arguments – Aziz May 31 '20 at 15:50
  • Does this answer your question? [Argparse: Required argument 'y' if 'x' is present](https://stackoverflow.com/questions/19414060/argparse-required-argument-y-if-x-is-present) – Богдан Туренко May 31 '20 at 15:51
  • 2
    @Aziz and БогданТуренко Please notice that this question is not about presence of an argument, but a **specific value** it gets – Tomerikoo May 31 '20 at 15:52

1 Answers1

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')
Nico Müller
  • 1,784
  • 1
  • 17
  • 37