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

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

问题描述

我有如下要求:

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

对于参数 prox ,我使用 action='store_true' 来检查它是否存在.我不需要任何论点.但是,如果设置了 --prox,我 要求 rport 和 lport 也是如此.有没有一种简单的方法可以使用 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天全站免登陆