Ron Halden
Ron Halden

Reputation: 35

Check if an argument is present and set a value accordingly

I am trying to write a program in Python that requires checking if an argument is present and then set a value to be used in the program accordingly. For example:

abc -a -b

Both -a and -b are optional. But -a provides a default value of some port number (say port 1234) to the program. But if -b is present, then the program must default to a different port number (say 2215).

How can I do this with argparse?

Upvotes: 2

Views: 112

Answers (1)

gmds
gmds

Reputation: 19885

You could do it like this:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-a',
                    action='store_const',
                    const=1234,
                    dest='port')

parser.add_argument('-b',
                    action='store_true',
                    dest='port_override')

args = parser.parse_args()

if args.port_override:
    args.port = 2215

print(args.port)

This tells argparse that if -a is specified, then the value 1234 will be stored in args.port. Also, if -b is specified, then args.port_override will be True. After performing argument parsing, we can check the value of args.port_override.

You could do this, too:

parser.add_argument('-b',
                    action='store_const',
                    const=2215
                    dest='port')

In this case, whichever comes second will override the other.

Upvotes: 3

Related Questions