Python argparse – Mutually exclusive group with default if no argument is given

You could have each of your actions update the same variable, supplying stdout as the default value for that variable.

Consider this program:

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument(
    '-s', '--stdout', action='store_const', dest="type", const="s", default="s")
group.add_argument(
    '-c', '--csv', action='store_const', dest="type", const="c")
group.add_argument(
    '-t', '--txt', action='store_const', dest="type", const="t")
args = parser.parse_args()
print args

Your code could look like:

if args.type == 's':
    ofile = sys.stdout
elif args.type == 'c':
    ofile = ...
...

First alternative:

Rather than arbitrarily choose one of the .add_argument()s to specify the default type, you can use parser.set_defaults() to specify the default type.

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-s', '--stdout', action='store_const', dest="type", const="s")
group.add_argument('-c', '--csv', action='store_const', dest="type", const="c")
group.add_argument('-t', '--txt', action='store_const', dest="type", const="t")
parser.set_defaults(type="s")
args = parser.parse_args()
print args

Second alternative:

Rather than specify the type as an enumerated value, you could store a callable into the type, and then invoke the callable:

import argparse

def do_stdout():
    # do everything that is required to support stdout
    print("stdout!")
    return
def do_csv():
    # do everything that is required to support CSV file
    print("csv!")
    return
def do_text():
    # do everything that is required to support TXT file
    print("text!")
    return

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-s', '--stdout', action='store_const', dest="type", const=do_stdout)
group.add_argument('-c', '--csv', action='store_const', dest="type", const=do_csv)
group.add_argument('-t', '--txt', action='store_const', dest="type", const=do_text)
parser.set_defaults(type=do_stdout)
args = parser.parse_args()
print args
args.type()

Leave a Comment

tech