如何使 argparse 仅使用一个参数,即使传递了多个参数?

How to make argparse work only with one argument, even if many are passed?

我的解析器结构:

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--search')
parser.add_argument('-t', '--status' action='store_true')
args = parser.parse_args()
if args.search:
    func(args.search)
if args.status:
    func1()

现在解析器可以接受这两个选项,-s query -t 有效。 我有两个问题:

  1. 如何仅在传递多个参数时才对第一个参数执行操作。 -s query -t 只需要结果

    if args.search:
        func(args.search)
    

    待完成。

  2. 如果传递了多个参数,如何抛出错误?

此处合适的工具是subparser;惯用用法与您当前建议的命令行不同。

def your_search_function(options):
    pass # do a search here

def your_status_function(options):
    pass # collect status here

def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparser(dest='action')

    search_parser = subparsers.add_parser('search')
    search_parser.set_defaults(func=your_search_function)

    status_parser = subparsers.add_parser('status')
    status_parser.set_defaults(func=your_status_function)

    results = parser.parse_args()
    results.func(options=results)

if __name__ == '__main__':
    main()

用法如下:

./yourcommand <global options> search <search options>

./yourcommand <global options> status <status options>

...因为它将 运行 的子命令作为参数而不是选项,所以不允许传递多个子命令,因此仅在使用时才提出问题的部分模棱两可。


全局选项可以像往常一样添加到parsersearch_parser 的特定搜索选项和 status_parser.

的特定状态选项