Python argparse : mutually exclusive arguments with optional and positional argument

前端 未结 2 1082
梦如初夏
梦如初夏 2020-12-11 22:24

I would like to get this with argparse library :

PROG --yesterday | begin-date [end-date]

I tried to combine mutual exclusion and argument

2条回答
  •  无人及你
    2020-12-11 22:44

    --yesterday is redundant, since it is just a shortcut for setting start_date to yesterday's day. Instead, let "yesterday" be an allowable value for start_date. In fact, you can generalize datetime to allow other abbreviations, for either argument, as desired. For example:

    def argument_date(str_date):
        # Not the most efficient to roundtrip like this, but
        # fits well with your existing code
        now = datetime.datetime.utcnow().date()
        if str_date == "yesterday":
            str_date = str(now - datetime.timedelta(1))
        elif str_date == "today"
            str_date = str(now)
    
        try:
            return datetime.strptime(str_date, "%Y-%m-%d").replace(tzinfo=pytz.utc)
        except ValueError as e:
            raise argparse.ArgumentTypeError(e)
    

    Once you've done this, your code simply becomes:

    parser = argparse.ArgumentParser(prog='PROG')
    parser.add_argument('start', type=argument_date, help='Start date (YYYY-MM-DD, yesterday, today)')
    parser.add_argument('end', type=argument_date, nargs='?', help='End date (YYYY-MM-DD, yesterday, today)')
    

提交回复
热议问题