Using the same option multiple times in Python’s argparse

Here’s a parser that handles a repeated 2 argument optional – with names defined in the metavar: parser=argparse.ArgumentParser() parser.add_argument(‘-i’,’–input’,action=’append’,nargs=2, metavar=(‘url’,’name’),help=’help:’) In [295]: parser.print_help() usage: ipython2.7 [-h] [-i url name] optional arguments: -h, –help show this help message and exit -i url name, –input url name help: In [296]: parser.parse_args(‘-i one two -i three four’.split()) Out[296]: … Read more

Call function based on argparse

Since it seems like you want to run one, and only one, function depending on the arguments given, I would suggest you use a mandatory positional argument ./prog command, instead of optional arguments (./prog –command1 or ./prog –command2). so, something like this should do it: FUNCTION_MAP = {‘top20’ : my_top20_func, ‘listapps’ : my_listapps_func } parser.add_argument(‘command’, … Read more

How can I constrain a value parsed with argparse (for example, restrict an integer to positive values)?

This should be possible utilizing type. You’ll still need to define an actual method that decides this for you: def check_positive(value): ivalue = int(value) if ivalue <= 0: raise argparse.ArgumentTypeError(“%s is an invalid positive int value” % value) return ivalue parser = argparse.ArgumentParser(…) parser.add_argument(‘foo’, type=check_positive) This is basically just an adapted example from the perfect_square … Read more

argparse subcommands with nested namespaces

If the focus is on just putting selected arguments in their own namespace, and the use of subparsers (and parents) is incidental to the issue, this custom action might do the trick. class GroupedAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): group,dest = self.dest.split(‘.’,2) groupspace = getattr(namespace, group, argparse.Namespace()) setattr(groupspace, dest, values) setattr(namespace, group, groupspace) There … Read more

argparse argument order

To keep arguments ordered, I use a custom action like this: import argparse class CustomAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): if not ‘ordered_args’ in namespace: setattr(namespace, ‘ordered_args’, []) previous = namespace.ordered_args previous.append((self.dest, values)) setattr(namespace, ‘ordered_args’, previous) parser = argparse.ArgumentParser() parser.add_argument(‘–test1’, action=CustomAction) parser.add_argument(‘–test2’, action=CustomAction) To use it, for example: >>> parser.parse_args([‘–test2’, ‘2’, ‘–test1’, ‘1’]) Namespace(ordered_args=[(‘test2’, … Read more

Python argparse: Is there a way to specify a range in nargs?

You could do this with a custom action: import argparse def required_length(nmin,nmax): class RequiredLength(argparse.Action): def __call__(self, parser, args, values, option_string=None): if not nmin<=len(values)<=nmax: msg=’argument “{f}” requires between {nmin} and {nmax} arguments’.format( f=self.dest,nmin=nmin,nmax=nmax) raise argparse.ArgumentTypeError(msg) setattr(args, self.dest, values) return RequiredLength parser=argparse.ArgumentParser(prog=’PROG’) parser.add_argument(‘-f’, nargs=”+”, action=required_length(2,3)) args=parser.parse_args(‘-f 1 2 3’.split()) print(args.f) # [‘1’, ‘2’, ‘3’] try: args=parser.parse_args(‘-f 1 … Read more

type=dict in argparse.add_argument()

Necroing this: json.loads works here, too. It doesn’t seem too dirty. import json import argparse test=”{“name”: “img.png”,”voids”: “#00ff00ff”,”0″: “#ff00ff00″,”100%”: “#f80654ff”}” parser = argparse.ArgumentParser() parser.add_argument(‘-i’, ‘–input’, type=json.loads) args = parser.parse_args([‘-i’, test]) print(args.input) Returns: {u’0′: u’#ff00ff00′, u’100%’: u’#f80654ff’, u’voids’: u’#00ff00ff’, u’name’: u’img.png’}

Customize argparse help message

First of all: capitalising those phrases flies in the face of convention, and argparse isn’t really tooled to help you change these strings easily. You have three different classes of strings here: boilerplate text from the help formatter, section titles, and help text per specific option. All these strings are localisable; you could just provide … Read more

Python argparse command line flags without arguments

As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false) import argparse parser = argparse.ArgumentParser() parser.add_argument(‘-w’, action=’store_true’) where action=’store_true’ implies default=False. Conversely, you could … Read more

argparse – disable same argument occurrences

I don’t think there is a native way to do it using argparse, but fortunately, argparse offers methods to report custom errors. The most elegant way is probably to define a custom action that checks for duplicates (and exits if there are). class UniqueStore(argparse.Action): def __call__(self, parser, namespace, values, option_string): if getattr(namespace, self.dest, self.default) is … Read more