Python argparse mutual exclusive group

add_mutually_exclusive_group doesn’t make an entire group mutually exclusive. It makes options within the group mutually exclusive. What you’re looking for is subcommands. Instead of prog [ -a xxxx | [-b yyy -c zzz]], you’d have: prog command 1 -a: … command 2 -b: … -c: … To invoke with the first set of arguments: prog … Read more

Simple argparse example wanted: 1 argument, 3 results

Here’s the way I do it with argparse (with multiple args): parser = argparse.ArgumentParser(description=’Description of your program’) parser.add_argument(‘-f’,’–foo’, help=’Description for foo argument’, required=True) parser.add_argument(‘-b’,’–bar’, help=’Description for bar argument’, required=True) args = vars(parser.parse_args()) args will be a dictionary containing the arguments: if args[‘foo’] == ‘Hello’: # code here if args[‘bar’] == ‘World’: # code here In … Read more

How can I pass a list as a command-line argument with argparse?

SHORT ANSWER Use the nargs option or the ‘append’ setting of the action option (depending on how you want the user interface to behave). nargs parser.add_argument(‘-l’,’–list’, nargs=”+”, help='<Required> Set flag’, required=True) # Use like: # python arg.py -l 1234 2345 3456 4567 nargs=”+” takes 1 or more arguments, nargs=”*” takes zero or more. append parser.add_argument(‘-l’,’–list’, … Read more

Parsing boolean values with argparse

I think a more canonical way to do this is via: command –feature and command –no-feature argparse supports this version nicely: Python 3.9+: parser.add_argument(‘–feature’, action=argparse.BooleanOptionalAction) Python < 3.9: parser.add_argument(‘–feature’, action=’store_true’) parser.add_argument(‘–no-feature’, dest=”feature”, action=’store_false’) parser.set_defaults(feature=True) Of course, if you really want the –arg <True|False> version, you could pass ast.literal_eval as the “type”, or a user defined … Read more