Reputation: 558
I want to create a program which selects users from a database between 2 dates given on the command line. I have:
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("--date1","-d1",help="Show users between dates",type=str)
group.add_argument("--date2","-d2",help="Show users between dates",type=str)
if args.date1 and args.date2:
DataCalculation.show_users_between_date(args.date1,args.date2)
And in my DataCalculation I have query to get users between 2 dates.
Unfortunately this solution doesnt work and I get error: argument --date2/-d2: not allowed with argument --date1/d1
I was running program like: py main.py -d1 1994-01-01 -d2 1995-12-31
I was thinking that I can split these 2 dates to list in function and give only 1 argument like: py main.py -d 1994-01-01 1995-12-31
, but this idea doesn't work too. Is there an easy way to use 2 arguments which have to be given together?
Upvotes: 1
Views: 1385
Reputation: 32944
You're looking for inclusivity, not exclusivity. You can accomplish that by using nargs=2
with one option, like your second case.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--date",
"-d",
nargs=2,
metavar=('start', 'end'), # Describes each argument
help="Show users between start and end dates",
)
args = parser.parse_args()
print(args)
Usage:
$ ./tmp.py -d 1994-01-01 1995-12-31
Namespace(date=['1994-01-01', '1995-12-31'])
$ ./tmp.py -d 1994-01-01
usage: tmp.py [-h] [--date start end]
tmp.py: error: argument --date/-d: expected 2 arguments
$ ./tmp.py -d 1994-01-01 1995-12-31 1998
usage: tmp.py [-h] [--date start end]
tmp.py: error: unrecognized arguments: 1998
$ ./tmp.py -h
usage: tmp.py [-h] [--date start end]
optional arguments:
-h, --help show this help message and exit
--date start end, -d start end
Show users between start and end dates
Upvotes: 2
Reputation: 43169
You could use
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("--daterange","-dr",help="Show users between dates",type=str)
args = parser.parse_args()
date1, date2 = args.daterange.split()
print(date1)
And then quotes around your arguments as in
python test.py -dr "1994-01-01 1995-12-31"
Which yields with the above snippet:
1994-01-01
Upvotes: 1