Python argparse mutually exclusive group with 1 vs 2 arguments

Viewed 2176

In my script to search text files (logs) I use argparse to grab command line arguments and define search criteria.

I use --df and --dt to define from => to period. I also want an optional --period that will override --df and --dt by using some defined strings parsed by an custom action (e.g. "week"). Now, I want --period to be mutually exclusive with --df AND --dt, but as far as I can tell, this is not possible with add_mutually_exclusive_group().

I have tried the following code, without success:

parser = argparse.ArgumentParser(description='Search the file')

dfgroup = parser.add_mutually_exclusive_group()
dfgroup.add_argument(
    '--df',
    type=dateparser.parse,
    metavar='DATETIME',
    help='date and/or time to search from'
)
dfgroup.add_argument(
    '--period',
    action='store', #should be a custom action
    metavar='PERIOD',
    help='the period to search within (mutually exclusive with --df and --dt)'
)
dtgroup = parser.add_mutually_exclusive_group()
dtgroup.add_argument(
    '--dt',
    type=dateparser.parse,
    metavar='DATETIME',
    help='date and/or time to search to'
)
dtgroup.add_argument(
    '--period',
    action='store', #should be a custom action
    metavar='PERIOD',
    help='the period to search within (mutually exclusive with --df and --dt)'
)

Is there any way I can make --period mutually exclusive with both --df and --dt arguments (and the other way around)?

1 Answers
Related