Diego Herranz
Diego Herranz

Reputation: 2947

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!

Upvotes: 5

Views: 2153

Answers (2)

unutbu
unutbu

Reputation: 880717

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)

Upvotes: 12

William Denman
William Denman

Reputation: 3164

I haven't used argparse before. But recently I saw a presentation on docopt https://github.com/docopt/docopt that blew me away.

Maybe give that a try?

Upvotes: 0

Related Questions