Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse: store_true and int at same time

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!

like image 209
Diego Herranz Avatar asked Jan 11 '23 23:01

Diego Herranz


1 Answers

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)
like image 89
unutbu Avatar answered Jan 31 '23 01:01

unutbu