Argparse Shortcut Option For Combining Other Options
Solution 1:
Keep it simple--the exclusive groups code you showed didn't exclude using both forms anyway. Try this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", help="Input file")
parser.add_argument("-o", "--output", help="Output file")
parser.add_argument("--io", help="Input and Output")
args = parser.parse_args()
if args.io:
assert args.inputisNoneand args.output isNone
args.input = args.output = args.io
else:
assert args.inputand args.output
Solution 2:
It is easier to explain why things don't work than to suggest a solution.
Yes, dest must be a string; there's no provision for a list or tuple of dest values. But your in_file = out_file = args.io addresses that issue just fine. You could have also used:
args.in_file=args.out_file = args.io
There's nothing wrong with massaging the args values after parsing.
argument_group is not designed for nesting, nor is it a way of adding 'any' (or 'and') logic to the mutually_exclusive_group. Maybe in the distant future there will be a way of defining a full set of logical combinations, but not now. Actually it isn't hard to do the tests; it's hard to define the API and the usage formatting.
Also keep in mind that mutually_exclusive_group is used to format the usage and test for co_ocurrance of arguments, while argument_group is used to group argument help lines. Two very different purposes.
If -i was a store_true argument then -io filename would be understood as -i -o filename. But translating it too -i filename -o filename is not in the current code (and probably not common enough to warrant a patch).
If you still want to use -i, -o and --io (I prefer -- for 2 character flags) I can suggest a couple of things:
write a custom usage that demonstrates what you want. If it is hard to write a clear usage, then your design is probably too complicated.
do your own
exclusive groupstesting after parsing.args.in_file is Noneis a good way of testing whether a flag has been used or not. Another possibility is to define defaults such that you don't care which combination the user uses.
Post a Comment for "Argparse Shortcut Option For Combining Other Options"