跳转到主要内容

最小化、易于使用的声明式cli工具

项目描述

最小声明式cli工具。

Codecov PyPI PyPI - Python Version
from decli import cli

data = {
    "prog": "myapp",
    "description": "Process some integers.",
    "arguments": [
        {
            "name": "integers",
            "metavar": "N",
            "type": int,
            "nargs": "+",
            "help": "an integer for the accumulator",
        },
        {
            "name": "--sum",
            "dest": "accumulate",
            "action": "store_const",
            "const": sum,
            "default": max,
            "help": "sum the integers (default: find the max)",
        },
    ],
}
parser = cli(data)
parser.parse_args()
>> parser.print_help()
usage: myapp [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
N           an integer for the accumulator

optional arguments:
-h, --help  show this help message and exit
--sum       sum the integers (default: find the max)
In [4]: args = parser.parse_args("--sum 3 2 1".split())

In [5]: args.accumulate(args.integers)
Out[5]: 6

关于

Decli是围绕argparse的最小封装。

当编写具有许多参数和子命令的大型应用程序时,这很有用,这样会更清晰。

这是一个用于快速创建与您的应用程序分离的界面的最小库。

可以像使用argparse一样使用任何参数,并且与之配合得很好。

忘记复制粘贴argparse函数,如果您像我一样懒惰,这个库应该非常有用!

已测试了许多情况,但可能并非所有内容都涵盖在内,因此如果您发现任何问题,请报告。

安装

pip install -U decli

或者

poetry add decli

用法

主cli

创建声明cli工具的字典。

接受argparse使用的相同参数,除了父级,将被忽略。

  • prog - 程序名称(默认:sys.argv[0])

  • usage - 描述程序用法的字符串(默认:从添加到解析器的参数生成)

  • description - 在参数帮助之前显示的文本(默认:无)

  • epilog - 在参数帮助之后显示的文本(默认:无)

  • formatter_class - 用于自定义帮助输出的类

  • prefix_chars - 前缀可选参数的字符集(默认:'-')

  • fromfile_prefix_chars - 应该读取额外参数的文件的前缀字符集合(默认:无)

  • argument_default - 参数的全局默认值(默认:无)

  • conflict_handler - 解决冲突可选参数的策略(通常不必要)

  • add_help - 向解析器添加 -h/–help 选项(默认:True)

  • allow_abbrev - 允许长选项缩写,如果缩写不歧义(默认:True)

更多信息请访问 argparse 页面

示例

data = {
    "prog": "myapp",
    "description": "This app does something cool",
    "epilog": "And that's it"
}

参数

它只是一个包含字典的列表。要添加别名,只需使用列表而不是字符串。

接受值

  • name: - 可以是名称或选项字符串列表,例如 foo 或 -f, –foo。

  • action - 在命令行遇到此参数时要执行的基本动作类型。

  • nargs - 应消耗的命令行参数数量。

  • const - 一些动作和 nargs 选择所需的常量值。

  • default - 如果命令行中缺少此参数,则产生的值。

  • type - 命令行参数应转换的类型。

  • choices - 包含参数允许值的容器。

  • required - 命令行选项是否可以省略(仅限可选参数)。

  • help - 简短描述该参数的作用。

  • metavar - 在使用消息中使用该参数的名称。

  • dest - 将添加到 parse_args() 返回的对象中的属性的名称。

有关 参数 的更多信息

示例

data = {
    "prog": "myapp",
    "description": "This app does something cool",
    "epilog": "And that's it",
    "arguments": [
        {
            "name": "--foo"
        },
        {
            "name": ["-b", "--bar"]
        }
    ]
}

子命令

它只是一个字典,其中最重要的键是 commands,这是一个命令列表。

接受值

  • title - 帮助输出中子解析器组的标题;如果有描述,则默认为“subcommands”,否则使用位置参数的标题

  • description - 帮助输出中子解析器组的描述,默认为 None

  • commands - 描述命令的字典列表。支持与 main cli 相同的参数。并且 func 非常重要。

  • prog - 在子命令帮助中显示的使用信息,默认为程序名称以及子解析器参数前的任何位置参数

  • action - 在命令行遇到此参数时要执行的基本动作类型

  • dest - 子命令名称将存储的属性的名称;默认为 None,不存储任何值

  • required - 是否必须提供子命令,默认为 False。

  • help - 帮助输出中子解析器组的帮助信息,默认为 None

  • metavar - 表示帮助中可用子命令的字符串;默认为 None,并以 {cmd1, cmd2, ..} 的形式显示子命令

有关 子命令 的更多信息

Func

通常在子命令中,指定它们指向哪个函数是有用的。这就是为什么每个命令都应该有这个参数。

当您构建一个执行多项操作的应用程序时,每个函数都应该使用这种方式映射到命令,使用 func 参数。

示例

from decli import cli

data = {
    "prog": "myapp",
    "description": "This app does something cool",
    "epilog": "And that's it",
    "subcommands": {
        "title": "main",
        "commands": [
            {
                "name": "sum",
                "help": "new project",
                "func": sum,
                "arguments": [
                    {
                        "name": "integers",
                        "metavar": "N",
                        "type": int,
                        "nargs": "+",
                        "help": "an integer for the accumulator",
                    },
                    {"name": "--name", "nargs": "?"},
                ],
            }
        ]
    }
}

parser = cli(data)
args = parser.parse_args(["sum 1 2 3".split()])
args.func(args.integers)  # Runs the sum of the integers

用于根据概念组对参数进行分组。这只会影响显示的 help,其他没有任何影响。

示例

data = {
    "prog": "app",
    "arguments": [
        {"name": "foo", "help": "foo help", "group": "group1"},
        {"name": "choo", "help": "choo help", "group": "group1"},
        {"name": "--bar", "help": "bar help", "group": "group2"},
    ]
}
parser = cli(data)
parser.print_help()
usage: app [-h] [--bar BAR] foo choo

optional arguments:
-h, --help  show this help message and exit

group1:
foo         foo help
choo        choo help

group2:
--bar BAR   bar help

独占组

互斥组允许从组中执行仅一个 optional 参数(以 -- 开头)。如果条件不满足,将显示错误。

示例

data = {
    "prog": "app",
    "arguments": [
        {"name": "--foo", "help": "foo help", "exclusive_group": "group1"},
        {"name": "--choo", "help": "choo help", "exclusive_group": "group1"},
        {"name": "--bar", "help": "bar help", "exclusive_group": "group1"},
    ]
}
parser = cli(data)
parser.print_help()
usage: app [-h] [--foo FOO | --choo CHOO | --bar BAR]

optional arguments:
-h, --help   show this help message and exit
--foo FOO    foo help
--choo CHOO  choo help
--bar BAR    bar help
In [1]: parser.parse_args("--foo 1 --choo 2".split())

usage: app [-h] [--foo FOO | --choo CHOO | --bar BAR]
app: error: argument --choo: not allowed with argument --foo

组和独占组

无法在具有 decli 的互斥组内部有组。

Decli 将通过引发 ValueError 来防止这样做。

可以使用argparse实现,但生成的帮助信息将不正确,排除功能将无法使用。

父级

有时,多个命令行界面共享一组常见的参数。

而不是重复这些参数的定义,可以将一个或多个包含所有共享参数的父命令行界面传递给cli的parents=argument

有关parents的更多信息,请参阅此处

示例

parent_foo_data = {
    "add_help": False,
    "arguments": [{"name": "--foo-parent", "type": int}],
}
parent_bar_data = {
    "add_help": False,
    "arguments": [{"name": "--bar-parent", "type": int}],
}
parent_foo_cli = cli(parent_foo_data)
parent_bar_cli = cli(parent_bar_data)

parents = [parent_foo_cli, parent_bar_cli]

data = {
    "prog": "app",
    "arguments": [
        {"name": "foo"}
    ]
}
parser = cli(data, parents=parents)
parser.print_help()
usage: app [-h] [--foo-parent FOO_PARENT] [--bar-parent BAR_PARENT] foo

positional arguments:
foo

optional arguments:
-h, --help            show this help message and exit
--foo-parent FOO_PARENT
--bar-parent BAR_PARENT

配方

子命令

from decli import cli

data = {
    "prog": "myapp",
    "formatter_class": argparse.RawDescriptionHelpFormatter,
    "description": "The software has subcommands which you can use",
    "subcommands": {
        "title": "main",
        "description": "main commands",
        "commands": [
            {
                "name": "all",
                "help": "check every values is true",
                "func": all
            },
            {
                "name": ["s", "sum"],
                "help": "new project",
                "func": sum,
                "arguments": [
                    {
                        "name": "integers",
                        "metavar": "N",
                        "type": int,
                        "nargs": "+",
                        "help": "an integer for the accumulator",
                    },
                    {"name": "--name", "nargs": "?"},
                ],
            }
        ],
    },
}
parser = cli(data)
args = parser.parse_args(["sum 1 2 3".split()])
args.func(args.integers)  # Runs the sum of the integers

最小化

此应用程序没有任何功能,但这是我们能拥有的最小功能

from decli import cli

parser = cli({})
parser.print_help()
usage: ipython [-h]

optional arguments:
-h, --help  show this help message and exit

位置参数

from decli import cli

data = {
    "arguments": [
        {
            "name": "echo"
        }
    ]
}
parser = cli(data)
args = parser.parse_args(["foo"])
In [11]: print(args.echo)
foo

带类型的位置参数

当指定类型时,参数将被视为该类型,否则将失败。

from decli import cli

data = {
    "arguments": [
        {
            "name": "square",
            "type": int
        }
    ]
}
parser = cli(data)
args = parser.parse_args(["1"])
In [11]: print(args.echo)
1

可选参数

from decli import cli

data = {
    "arguments": [
        {
            "name": "--verbose",
            "help": "increase output verbosity"
        }
    ]
}
parser = cli(data)
args = parser.parse_args(["--verbosity 1"])
In [11]: print(args.verbosity)
1

In [15]: args = parser.parse_args([])

In [16]: args
Out[16]: Namespace(verbose=None)

标志

标志是选项的唯一布尔子集(True/False)。

from decli import cli

data = {
    "arguments": [
        {
            "name": "--verbose",
            "action": "store_true",  # defaults to False
        },
        {
            "name": "--noisy",
            "action": "store_false",  # defaults to True
        }
    ]
}
parser = cli(data)

短选项

用于添加选项的简短版本。

data = {
    "arguments": [
        {
            "name": ["-v", "--verbose"],
            "help": "increase output verbosity"
        }
    ]
}

分组

这仅使用参数才能实现。

仅影响帮助信息的显示方式。您可能正在寻找子命令。

data = {
    "prog": "mycli",
    "arguments": [
        {
            "name": "--save",
            "group": "main",
            "help": "This save belongs to the main group",
        },
        {
            "name": "--remove",
            "group": "main",
            "help": "This remove belongs to the main group",
        },
    ],
}
parser = cli(data)
parser.print_help()
usage: mycli [-h] [--save SAVE] [--remove REMOVE]

optional arguments:
-h, --help       show this help message and exit

main:
--save SAVE      This save belongs to the main group
--remove REMOVE  This remove belongs to the main group

独占组

这仅使用可选参数才能实现。

data = {
    "prog": "mycli",
    "arguments": [
        {
            "name": "--save",
            "exclusive_group": "main",
            "help": "This save belongs to the main group",
        },
        {
            "name": "--remove",
            "exclusive_group": "main",
            "help": "This remove belongs to the main group",
        },
    ],
}
parser = cli(data)
parser.print_help()
usage: mycli [-h] [--save SAVE | --remove REMOVE]

optional arguments:
-h, --help       show this help message and exit
--save SAVE      This save belongs to the main group
--remove REMOVE  This remove belongs to the main group

结合位置参数和可选参数

data = {
    "arguments": [
        {
            "name": "square",
            "type": int,
            "help": "display a square of a given number"
        },
        {
            "name": ["-v", "--verbose"],
            "action": "store_true",
            "help": "increase output verbosity"
        }
    ]
}
parser = cli(data)

args = parser.parse_args()
answer = args.square**2
if args.verbose:
    print(f"the square of {args.square} equals {answer}")
else:
    print(answer)

更多示例

测试目录中的examples.py包含来自argparse文档的许多示例

贡献

  1. 克隆存储库

  2. 安装依赖项

poetry install
  1. 运行测试

./scripts/tests

贡献

欢迎提交PR!

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定要选择哪个,请了解更多关于安装包的信息。

源分发

decli-0.6.2.tar.gz (7.4 kB 查看哈希值)

上传时间

构建分发

decli-0.6.2-py3-none-any.whl (7.9 kB 查看哈希值)

上传时间 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页