Argparse有条件的必需参数

Argparse有条件的必需参数

本文介绍了Python Argparse有条件的必需参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经进行了尽可能多的研究,但是我还没有找到仅在特定条件下才需要某些cmdline参数的最佳方法,在这种情况下,只有给出了其他参数.这是我最基本的操作:

I have done as much research as possible but I haven't found the best way to make certain cmdline arguments necessary only under certain conditions, in this case only if other arguments have been given. Here's what I want to do at a very basic level:

p = argparse.ArgumentParser(description='...')
p.add_argument('--argument', required=False)
p.add_argument('-a', required=False) # only required if --argument is given
p.add_argument('-b', required=False) # only required if --argument is given

从我所见,其他人似乎只是在末尾添加自己的支票:

From what I have seen, other people seem to just add their own check at the end:

if args.argument and (args.a is None or args.b is None):
    # raise argparse error here

是否可以在argparse软件包中本地执行此操作?

Is there a way to do this natively within the argparse package?

推荐答案

一段时间以来,我一直在寻找这种问题的简单答案.您需要做的就是检查'--argument'是否在sys.argv中,因此基本上对于您的代码示例,您可以这样做:

I've been searching for a simple answer to this kind of question for some time. All you need to do is check if '--argument' is in sys.argv, so basically for your code sample you could just do:

import argparse
import sys

if __name__ == '__main__':
    p = argparse.ArgumentParser(description='...')
    p.add_argument('--argument', required=False)
    p.add_argument('-a', required='--argument' in sys.argv) #only required if --argument is given
    p.add_argument('-b', required='--argument' in sys.argv) #only required if --argument is given
    args = p.parse_args()

这种方式required接收TrueFalse取决于用户是否使用过--argument.已经进行了测试,似乎可以正常工作,并保证-a-b在彼此之间具有独立的行为.

This way required receives either True or False depending on whether the user as used --argument. Already tested it, seems to work and guarantees that -a and -b have an independent behavior between each other.

这篇关于Python Argparse有条件的必需参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 16:34