Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, using argparse, allow only positive integers

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 function in the docs on argparse.


type would be the recommended option to handle conditions/checks, as in Yuushi's answer.

In your specific case, you can also use the choices parameter if your upper limit is also known:

parser.add_argument('foo', type=int, choices=xrange(5, 10))

Note: Use range instead of xrange for python 3.x


The quick and dirty way, if you have a predictable max as well as min for your arg, is use choices with a range

parser.add_argument('foo', type=int, choices=xrange(0, 1000))

A simpler alternative, especially if subclassing argparse.ArgumentParser, is to initiate the validation from inside the parse_args method.

Inside such a subclass:

def parse_args(self, args=None, namespace=None):
    """Parse and validate args."""
    namespace = super().parse_args(args, namespace)
    if namespace.games <= 0:
         raise self.error('The number of games must be a positive integer.')
    return namespace

This technique may not be as cool as a custom callable, but it does the job.


About ArgumentParser.error(message):

This method prints a usage message including the message to the standard error and terminates the program with a status code of 2.


Credit: answer by jonatan