I'm using argparse for cli arguments. I want an argument -t
, to perform a temperature test. I also want to specify the period of temperature measurements.
I want:
python myscript.py -t
to perform a measurement every 60 seconds,
python myscript.py -t 30
to perform a measurement every 30 seconds and,
python myscript.py
not to do the temperature measurement.
Right now I am doing it like this:
parser.add_argument('-t', '--temperature',
help='performs temperature test (period in sec)',
type=int, default=60, metavar='PERIOD')
The problem is that I can not distinguish between python myscript.py
and python myscript.py -t
.
It would like to be able to do something like action='store_true'
and type=int
at the same time. Is it possible? Any other way to do it?
Thanks!
Use the const
parameter:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'-t', '--temperature',
help='performs temperature test (period in sec)',
type=int,
nargs='?',
const=60, # Default value if -t is supplied
default=None, # Default value if -t is not supplied
metavar='PERIOD')
args = parser.parse_args()
print(args)
% test.py
Namespace(temperature=None)
% test.py -t
Namespace(temperature=60)
% test.py -t 30
Namespace(temperature=30)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With