1

I have a script where the user can input two date values for a date range to run my script. If they don't input two values, I want my script to run with a default date range. How can I do this?

Right now this is what I have:

parser = argparse.ArgumentParser()
parser.add_argument('start', type=str, help='Start date YYYY-MM-DD')
parser.add_argument('end', type=str, help='End date YYYY-MM-DD')
args = parser.parse_args()

start = args.start
stop = args.end

** if the two dates are invalid or not provided by user: ** 
start = '20220101'
stop = '20220416'
3
  • 1
    use default= arg for the add_argument Commented Aug 5, 2022 at 15:35
  • 1
    parser.add_argument('end', type=str, help='End date YYYY-MM-DD', default='2022-10-05)` Commented Aug 5, 2022 at 15:35
  • This gets tricky, as you can't get a default start without using the default end, as myscript 20220805 will assume it was given a starting date. Commented Aug 5, 2022 at 15:47

1 Answer 1

3

you can use the argument default

parser = argparse.ArgumentParser()
parser.add_argument('start', type=str, default='20220101', help='Start date YYYY-MM-DD')
parser.add_argument('end', type=str, default='20220416', help='End date YYYY-MM-DD')
args = parser.parse_args()

start = args.start
stop = args.end 
Sign up to request clarification or add additional context in comments.

1 Comment

Specifying a default argument isn't sufficient, You also need to use nargs='?', as positional parameters are required by default.

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.