限制命令行选项的值 [英] Restricting values of command line options
问题描述
如何限制argparse选项的值?
How do I restrict the values of the argparse options?
在下面的代码sau
中,选项仅应接受0
或1
,而bg
仅应允许整数.我该如何实施?
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='<Required> Set flag',required=True)
parser.add_argument('-bg','--base_g',action='store',dest='base_g',help='<Required> Base g',required=True)
results = parser.parse_args() # collect cmd line args
set = results.set
base_g = results.base_g
if __name__ == '__main__':
main()
推荐答案
您可以使用的> type=
和 choices=
参数href ="https://docs.python.org/library/argparse.html#argparse.ArgumentParser.add_argument" rel ="nofollow noreferrer"> add_argument
.要仅接受'0'
和'1'
,请执行以下操作:
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"})
要只接受整数,您可以这样做:
And to accept only integer numbers, you'd do:
parser.add_argument(…, type=int)
请注意,在choices
中,必须以指定为type
参数的类型提供选项.因此,要检查整数和仅允许0
和1
,您可以这样做:
Note that in choices
, you 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:
parser.add_argument(…, type=int, choices={0, 1})
示例:
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument("-p", type=int, choices={0, 1})
>>> parser.parse_args(["-p", "0"])
Namespace(p=0)
这篇关于限制命令行选项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!