Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: combine multiple-value argument with default and const

I've been looking for solution to add an argument that would behave as action='store_const', but would take multiple values.

So that if I don't pass it at all, it should has no value(or some value), if I pass it without value it should has default value, and if I pass it with value(s) it should be a list of these values.

e.g.

parser.parse_args(''.split())
parser.parse_args('-a'.split())
parser.parse_args('-a 1 2 3'.split())

should result in

[None]
[0]
[1, 2, 3]
like image 713
Nik Avatar asked Apr 05 '13 14:04

Nik


1 Answers

Not too hard:

parser = argparse.ArgumentParser()
parser.add_argument('-a',default=[None],action='store',type=int,nargs='*')
print parser.parse_args(''.split())
print parser.parse_args('-a'.split())
print parser.parse_args('-a 1 2 3'.split())

If you want to special case the -a with no additional arguments, there is no way to do that without using a custom Action:

import argparse
class MyAction(argparse.Action):
    def __call__(self,parser,namespace,values,option_string=None):
        if not values:
            setattr(namespace,self.dest,[0])
        else:
            setattr(namespace,self.dest,values)

parser = argparse.ArgumentParser()
parser.add_argument('-a',default=[None],action=MyAction,type=int,nargs='*')
print parser.parse_args(''.split())
print parser.parse_args('-a'.split())
print parser.parse_args('-a 1 2 3'.split())
like image 144
mgilson Avatar answered Oct 21 '22 17:10

mgilson