1

I have it to where if the user doesn't input a num2, it will take 1 as a default number. However, I'm also trying to implement where if the user DOES input a number, it has to be above 0.

import argparse
group = parser.add_mutually_exclusive_group()

group.add_argument('-n2', '--num2', action='store_true', default=1, choices=range(0))

I've looked around and found that choices=ranges allows me to set a range for the number, however, i get an error saying

TypeError: __init__() got an unexpected keyword argument 'choices'
Rae Leng
  • 75
  • 8
  • Maybe the error refers to a bad argument rather than a bad keyword. Try a non-empty container, like `range(5)`. – luther Nov 24 '20 at 04:39

2 Answers2

4

You can use type to check for positive integer input as follows:

import argparse


def check_positive(value):
    try:
        value = int(value)
        if value <= 0:
            raise argparse.ArgumentTypeError("{} is not a positive integer".format(value))
    except ValueError:
        raise Exception("{} is not an integer".format(value))
    return value


parser = argparse.ArgumentParser(...)
parser.add_argument('--foo', type=check_positive)

args = parser.parse_args()
print('args: {}'.format(args.foo))
Minh Nguyen
  • 755
  • 5
  • 11
1

After making few parameter changes i was able to resolve the issues. I'm not sure if this is the same thing that you want though

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-n2', '--num2',  default=1, type=int,choices=range(0))

I just removed action and it works fine. I'm also new to python so let me know if its not what you needed

Sachin Rajput
  • 238
  • 7
  • 26