【问题标题】:Python argparse module usagePython argparse 模块用法
【发布时间】:2017-05-07 06:56:54
【问题描述】:

我有一个程序是这样调用的:

program.py add|remove|show 

这里的问题是,根据添加/删除/显示命令,它需要可变数量的参数,就像这样:

program.py add "a string" "another string"
program.py remove "a string"
program.py show

所以,'add' 命令需要 2 个字符串参数,而 'remove' 命令只需要 1 个参数,而 'show' 命令不需要任何参数。 我知道如何使用模块 argparse 制作一个基本的参数解析器,但我没有太多经验,所以我从这个开始:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["add", "remove", "show"])

但我不知道如何继续以及如何根据命令实现此功能。提前致谢。

【问题讨论】:

    标签: python arguments argparse


    【解决方案1】:

    您正在寻找 argparse 的子解析器...

    parser = argparse.ArgumentParser(prog='PROG')
    subparsers = parser.add_subparsers(help='sub-command help')
    
    # create the parser for the "add" command
    parser_add = subparsers.add_parser('add', help='add help')
    # [example] add an argument to a specific subparser
    parser_add.add_argument('bar', type=int, help='bar help')
    
    # create the parser for the "remove" command
    parser_remove = subparsers.add_parser('remove', help='remove help')
    
    # create the parser for the "show" command
    parser_show = subparsers.add_parser('show', help='show help')
    

    这个示例代码被盗用了语言reference documentation的很少修改。

    【讨论】:

    • 如何检查选择了哪个选项并获取对应的变量?
    • @xBlackout -- 我链接的文档也对此提供了建议......在页面上搜索以“处理子命令的一种特别有效的方式”开头的句子。 tl;博士;是您可以使用set_defaults 根据选择的子解析器将函数附加到命名空间。然后您只需调用该函数来执行与所选子解析器关联的操作。
    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 2012-08-23
    • 2011-09-30
    • 2013-11-11
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2017-12-02
    相关资源
    最近更新 更多