Argparse:如果存在"x",则必需的参数"y" [英] Argparse: Required argument 'y' if 'x' is present

查看:79
本文介绍了Argparse:如果存在"x",则必需的参数"y"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下要求:

./xyifier --prox --lport lport --rport rport

对于参数prox,我使用action ='store_true'来检查它是否存在. 我不需要任何论点.但是,如果设置了--prox,我也需要.有没有一种简单的方法可以使用argparse做到这一点,而无需编写自定义条件编码.

for the argument prox , I use action='store_true' to check if it is present or not. I do not require any of the arguments. But, if --prox is set I require rport and lport as well. Is there an easy way of doing this with argparse without writing custom conditional coding.

更多代码:

non_int.add_argument('--prox', action='store_true', help='Flag to turn on proxy')
non_int.add_argument('--lport', type=int, help='Listen Port.')
non_int.add_argument('--rport', type=int, help='Proxy port.')

推荐答案

不,在argparse中没有任何选项可以使彼此成为包含的选项集.

No, there isn't any option in argparse to make mutually inclusive sets of options.

最简单的解决方法是:

if args.prox and (args.lport is None or args.rport is None):
    parser.error("--prox requires --lport and --rport.")

这篇关于Argparse:如果存在"x",则必需的参数"y"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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