Argparse optional positional arguments?

Use nargs=”?” (or nargs=”*” if you need more than one dir) parser.add_argument(‘dir’, nargs=”?”, default=os.getcwd()) extended example: >>> import os, argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument(‘-v’, action=’store_true’) _StoreTrueAction(option_strings=[‘-v’], dest=”v”, nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None) >>> parser.add_argument(‘dir’, nargs=”?”, default=os.getcwd()) _StoreAction(option_strings=[], dest=”dir”, nargs=”?”, const=None, default=”/home/vinay”, type=None, choices=None, help=None, metavar=None) >>> parser.parse_args(‘somedir -v’.split()) Namespace(dir=”somedir”, v=True) >>> … 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