Python argparse value range help message appearance

前端 未结 4 582
挽巷
挽巷 2021-02-08 07:46

I have an argument for a program that is an integer from 1-100 and I just don\'t like the way that it shows up in the -h help message when using argparse (it literally lists 0,

4条回答
  •  醉梦人生
    2021-02-08 08:15

    Here are a couple ways you can do it instead

    def parseCommandArgs():
        parser = argparse.ArgumentParser()
        parser.add_argument('-i', dest='myDest', choices=range(1,101), type=int, required=True, metavar='INT[1,100]', help='my help message')
        return parser.parse_args()
    

    You can also use action instead, which I highly recommend since it allows more customization

    def verify():
        class Validity(argparse.Action):
            def __call__(self, parser, namespace, values, option_string=None):
                if values < 1 or values > 100:
                    # do something
                    pass
        return Validity
    
    def parseCommandArgs():
        parser = argparse.ArgumentParser()
        parser.add_argument('-i', dest='myDest', required=True, metavar='INT[1,100]', help='my help message', action=verify())
        return parser.parse_args()
    

提交回复
热议问题