简体   繁体   中英

Python argparse mutually exclusive group with 1 vs 2 arguments

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 (eg "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)?

If you are absolutely sure and comfortable with this solution, I have a work around. Use nargs in add_argument like this

import argparse
parser = argparse.ArgumentParser(description="Hello")
group = parser.add_mutually_exclusive_group()
group.add_argument('--period', action='store')
group.add_argument('--df_dt', nargs='+')
args = parser.parse_args()

Provide this when executing your script

program.py --period <period>
program.py --df_dt <df> <dt>

Then access the arguments using

df = args.df_dt[0]
dt = args.df_dt[1]

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM