开发者社区> 问答> 正文

Python argparse require选项,取决于定义的标志

如果使用方法A运行脚本,则将使用默认文件或使用-f/ 定义的文件--file。该脚本检查文件是否存在,并且一切正常。

现在,如果我使用方法B运行脚本,则该脚本不需要该文件,但是将检查默认选项,并且如果不存在该默认选项,则argparse函数将引发异常并退出脚本。

如何配置argparse以使其-f可选(如果-b已定义)并要求它(如果-a已定义)?

展开
收起
游客ufivfoddcd53c 2020-01-04 14:43:18 914 0
1 条回答
写回答
取消 提交回答
  • 您可以使用y / be作为子命令定义子解析器,或者为a声明第二个解析器实例。就像是:

    parser = argparse.ArgumentParser(
        description="An example",
        formatter_class=argparse.RawTextHelpFormatter
    )
    # ensure either option -a or -b only
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-a", "--ay", help="Method A, requires file.",
                       action='store_true')
    group.add_argument("-b", "--be", help="Method B, no file required.",
                       action='store_true')
    # define a parser for option -a
    parser_a = argparse.ArgumentParser()
    parser_a.add_argument("-f", "--file", help="A file, used with method A.",
                          type=check_file, required=True)
    parser_a.add_argument("-a", "--ay", help="Method A, requires file.",
                          action='store_true')
    
    # first parse - get either -a/-b
    args = parser.parse_known_args(sys.argv[1:])
    # if -a, use the second parser to ensure -f is in argument
    # note parse_known_args return tuple, the first one is the populated namespace
    if args[0].ay:
        args = parser_a.parse_args(sys.argv[1:])
    
    2020-01-04 14:43:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载