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 argparseparser = 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.stdoutelif 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 argparseparser = 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 argparsedef do_stdout(): # do everything that is required to support stdout print("stdout!") returndef do_csv(): # do everything that is required to support CSV file print("csv!") returndef do_text(): # do everything that is required to support TXT file print("text!") returnparser = 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 argsargs.type()
You can "cheat" with sys.argv :
import sysdef main(): if len(sys.argv) == 2 and sys.argv[1] not in ['-s', '-c', '-t', '-h']: filename = sys.argv[1] print "mode : stdout", filename else: parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-s', '--stdout') group.add_argument('-c', '--csv') group.add_argument('-t', '--txt') args = parser.parse_args() if args.stdout: print "mode stdout :", args.stdout if args.csv: print "mode csv :", args.csv if args.txt: print "mode txt :", args.txtif __name__ == "__main__": main()