限制命令行选项的值 [英] Restricting values of command line options

查看:32
本文介绍了限制命令行选项的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制 argparse 选项的值?

在下面的代码中 sau 选项应该只接受多个 01 并且 bg 应该只接受允许一个整数.我该如何实施?

导入操作系统导入系统,getopt导入参数解析定义主():parser = argparse.ArgumentParser(description='测试脚本')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() # 收集命令行参数设置 = 结果.setbase_g = results.base_g如果 __name__ == '__main__':主要的()

解决方案

您可以使用 type=choices=add_argument<的代码>参数/a>.要仅接受 '0''1',您可以:

parser.add_argument(..., choice={"0", "1"})

如果只接受整数,你会这样做:

parser.add_argument(..., type=int)

请注意,在choices 中,您必须以您指定为type 参数的类型提供选项.所以要检查整数只允许01,你会这样做:

parser.add_argument(..., type=int, choice={0, 1})

示例:

<预><代码>>>>导入参数解析>>>解析器 = argparse.ArgumentParser()>>>_ = parser.add_argument("-p", type=int, choice={0, 1})>>>parser.parse_args(["-p", "0"])命名空间(p=0)

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='<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()

解决方案

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)

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})

Example:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument("-p", type=int, choices={0, 1})
>>> parser.parse_args(["-p", "0"])
Namespace(p=0)

这篇关于限制命令行选项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆