I'm writing a Python script to process a machine-readable file and output a human-readable report on the data contained within.
I would like to give the option of outputting the data to stdout (-s)
(by default) or to a txt (-t)
or csv (-c)
file. I would like to have a switch for the default behaviour, as many commands do.
In terms of Usage:
, I'd like to see something like script [-s | -c | -t] input file
, and have -s
be the default if no arguments are passed.
I currently have (for the relevant args, in brief):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-s', '--stdout', action='store_true')
group.add_argument('-c', '--csv', action='store_true')
group.add_argument('-t', '--txt', action='store_true')
args = parser.parse_args()
if not any((args.stdout, args.csv, args.txt)):
args.stdout = True
So if none of -s
, -t
, or -c
are set, stdout (-s)
is forced to True, exactly as if -s
had been passed.
Is there a better way to achieve this? Or would another approach entirely be generally considered 'better' for some reason?
Note: I'm using Python 3.5.1/2 and I'm not worried about compatibility with other versions, as there is no plan to share this script with others at this point. It's simply to make my life easier.