【问题标题】:Conditional argparse with choice option带有选择选项的条件 argparse
【发布时间】:2019-04-09 23:21:06
【问题描述】:

以下是我在模块中编写的三个参数。

parser.add_argument('--Type',type=str,choices=['a','b','c'],help='Options include: a,b,c.',required=True)

parser.add_argument('--Input',default=False,help='Generate input files',required=False)

parser.add_argument('--Directory',default=False,help='Secondary directory',required='--Input' in sys.argv)

--Type 可以使用三个选项:a、b、c。

目前,我已将其设置为,如果 --Directory 为真,则需要 --Input 为真。

但是,我想向 --Directory 添加一个附加条件以要求 --Type 为 == 'c'。

如何更改 --Directory 参数中的 required 选项,使其同时需要 --Input 和 --Type == 'c'?

【问题讨论】:

    标签: python conditional argparse


    【解决方案1】:

    将参数解析与您的需求分离。

    parser.add_argument('--Type', choices=['a','b','c'], required=True)
    parser.add_argument('--Input', action='store_true')
    parser.add_argument('--Directory', action='store_true')
    
    args = parser.parse_args()
    
    if args.Directory and args.Type != 'c' and not args.input:
        raise argparse.ArgumentError("--Directory requires --Type c and --Input")
    

    (注意action='store_true' 会自动设置type=booldefault=False。)

    【讨论】:

    • 小写字母选项不是惯用的吗?
    • 取决于您尝试遵循的成语。我不知道任何使用大写的选项名称,但这并不意味着它们不存在。也就是说,是的,GNU 风格的长选项通常不以大写字母开头。
    • 'a','b','c' 只是这个问题的占位符。我隐藏了其中的一些信息。我不知道 action='store_true'。这很有帮助!
    • @AndrewHamel 我认为 gmds 指的是您选择的 --Type 而不是更常见的名称,例如 --type
    • 我明白了。如果我有其他 parser.add_arguments,此解决方案是否也有效。例如,我看不到用户总是需要使用 --Directory 标志
    【解决方案2】:

    我不会将required 参数用于其中任何一个,它很容易出错并且可读性不强。只需在解析后检查参数的有效性即可。

    import argparse
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument('--Type', type=str, choices=['a','b','c'], help='Options include: a,b,c.', required=True)
        parser.add_argument('--Input', default=False, help='Generate input files', required=False)
        parser.add_argument('--Directory', default=False, help='Secondary directory', required=False)
        parsed_args = parser.parse_args()
        if parsed_args.Directory and not (parsed_args.Input and parsed_args.Type == 'c'):
            parser.error('option --Directory requires --Input and --Type c.')
    

    【讨论】:

      【解决方案3】:

      这不是最漂亮的,但您可以查看 --Type 旁边的参数并检查它是否等于 'c',如下所示:

      parser.add_argument('--Directory', default=False, help='secondary directory',
                          required=('--Type' in sys.argv and
                                    sys.argv[sys.argv.index('--Type') + 1] == 'c')
                         )
      

      【讨论】:

      • 谢谢,我考虑在 argparser 之外添加条件语句。
      【解决方案4】:

      我认为也可以这样做

      import sys
      
      # Your past code here
      
      args = parser.parse_args()
      
      type = args.Type
      input = args.Input
      directory = args.Directory
      
      if directory:
          if input != 'c':
              print 'error in argument'
              sys.exit(1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-06
        • 2020-10-26
        • 2016-08-11
        • 1970-01-01
        • 2017-03-12
        • 2018-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多