如何在Python中使用argparse模块处理参数逻辑

如何在Python中使用argparse模块处理参数逻辑,python,terminal,arguments,argparse,Python,Terminal,Arguments,Argparse,我正在编写一个脚本,希望能够以两种模式运行: --testall-不需要额外的参数 --测试-参数:-f,-t,-sm必需 但我不知道如何使用argparse模块编写该逻辑。思想? 当我跑的时候 python3测试_argparse.py——testall 它抛出: usage: test_argparse.py [-h] [--testall TESTALL | --test TEST] [-f FROM] [-t TO] [-sm {prese

我正在编写一个脚本,希望能够以两种模式运行:

  • --testall-不需要额外的参数
  • --测试-参数:-f,-t,-sm必需
  • 但我不知道如何使用argparse模块编写该逻辑。思想? 当我跑的时候

    python3测试_argparse.py——testall

    它抛出:

    usage: test_argparse.py [-h] [--testall TESTALL | --test TEST] [-f FROM]
                            [-t TO] [-sm {preserve,noresdir}]
    test_argparse.py: error: argument --testall: expected one argument
    
    到目前为止

    import argparse
    
    parser = argparse.ArgumentParser(description="Tests fast copy operation. Checks MD5 hashes, file and directory "
                                                 "permissions, sync modes (sync, keep, recopy, resync, preserve, resdir, "
                                                 "noresdir) and outputs the result to MySQL database on Nemo")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--testall", help="tests copy operations between all available zones", type=str)
    group.add_argument("--test", help="tests copy operation between specific zones", type=str)
    
    parser.add_argument("-f", "--from", help="name of the zone to copy from")
    parser.add_argument("-t", "--to", help="name of the zone to copy to")
    parser.add_argument("-sm", "--syncmode", help="mode to use when copying", choices=['preserve', 'noresdir'])
    args = parser.parse_args()
    
    if __name__ == "__main__":
        print(vars(args))
        if args.testall:
            print('Testing TESTALL mode')
        elif args.test:
            print('Testing TEST mode')
        else:
            print('Testing everything else')
    

    首先,将
    testall
    test
    设置为“store\u true”。这样他们就不需要争论了。或者进行
    test
    a
    nargs=3
    并忽略其他部分。您可能仍然需要实现某种解析后测试
    argparse
    仅提供互斥的
    xor
    测试和子parser。提供逻辑默认值还可以消除花哨测试的需要。请记住,您希望API对您的用户来说清晰易懂。很难解释复杂的情况,特别是在简明的
    用法
    行中。我添加了
    组。添加参数(“--test”,help=“tests copy operation from specific zones”,action='store\u true')
    ,最后还添加了
    uargs=vars(args)print(uargs),如果uargs['testall']为true:print('Testing Testing Testing testall mode'))elif uargs['test']:如果[uargs['from']、uargs['to']、uargs['syncmode']]:parser.error('使用--test时,必须指定--from、--to和--syncmode参数!')sys.exit(1)print('Testing test mode'))else:print('测试所有其他参数)