Source From Here
Question
How do I restrict the values of the argparse options?
In the below code sau option should only accept a number of 0 or 1 and bg should only allow an integer. How can I implement this?
How-To
You can use the type and choices arguments of add_argument. To accept only '0' and '1', you'd do:
And to accept only integer numbers, you'd do:
Note that in choices, you’ll have to give the options in the type you specified as the type-argument. So to check for integers and allow only 0 and 1, you'd do:
Example:
Question
How do I restrict the values of the argparse options?
In the below code sau option should only accept a number of 0 or 1 and bg should only allow an integer. How can I implement this?
- import os
- import sys, getopt
- import argparse
- def main ():
- parser = argparse.ArgumentParser(description='Test script')
- parser.add_argument('-sau','--set',action='store',dest='set',help='
Set flag' ,required=True) - parser.add_argument('-bg','--base_g',action='store',dest='base_g',help='
Base g' ,required=True) - results = parser.parse_args() # collect cmd line args
- set = results.set
- base_g = results.base_g
- if __name__ == '__main__':
- main()
You can use the type and choices arguments of add_argument. To accept only '0' and '1', you'd do:
- parser.add_argument(…, choices={"0", "1"})
- parser.add_argument(…, type=int)
- parser.add_argument(…, type=int, choices={0, 1})
沒有留言:
張貼留言