argparse deco-argparse的语法糖

argparse-deco的Python项目详细描述


argparse deco基本上是argparse使用的语法糖 装饰师。尽管它继承了 Kevin L.Mitchell的cliu工具https://github.com/klmitch/cli_tools),它不共享其源 代码。

它的主要区别是滥用python类的可能性 使用嵌套子命令和 使用inspect.signature自动生成命令参数 从函数的签名。

简单的cli

api足以使用三个导入。

>>> from argparse_deco import CLI, Arg, Flag

作为一个简单cli的示例,可以使用cli作为 转换函数:

>>> @CLI(prog="prog")
... def prog(
...         integers: Arg(metavar='N', nargs='+', type=int,
...                       help="an integerfor the accumulator"),
...         accumulate: Arg('--sum', action='store_const', const=sum,
...                         help="sum the integers (default: find the max)"
...                         )=max):
...     """Process some integers."""
...     print(accumulate(integers))

decoratorcli将函数prog转换为命令 实例。有效地prog接受一些命令行参数,如 [“1”,“2”,“4”,“–sum”]作为cli_args关键字,它被转换 通过argparse模块将参数整型累加 传递到原始函数prog

>>> prog(["1", "2", "4", "--sum"])
7
>>> prog(["1", "2", "4"])
4

为了获得ArgumentParser实例,prog拥有 方法设置分析器

>>> parser = prog.setup_parser()
>>> print(parser)
ArgumentParser(prog='prog', usage=None, description='Process some integers.', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
>>> parser.print_usage()
usage: prog [-h] [--sum] N [N ...]
>>> parser.print_help()
usage: prog [-h] [--sum] N [N ...]
<BLANKLINE>
Process some integers.
<BLANKLINE>
positional arguments:
  N           an integerfor the accumulator
<BLANKLINE>
optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)

参数

以便将函数的参数处理为 argumentparser参数,它们必须由arg注释。基本上 arg允许将类型作为关键字,并允许任意关键字参数 它几乎是以不变的方式传递给ArgumentParser.add_argument。

分析器

ArgumentParser实例的描述通常是 函数的docstring,可以使用 cli.parserdecorator,它接受任何参数 会的。

参数可以使用组而不是 参数的注释,它接受组名作为第一个关键字 类型为第二个。可以自定义组(标题, 说明)使用cli.groupdecorator:

>>> @CLI("prog")
... @CLI.group('foo', title="Foo", description="Foo group")
... def prog(
...         bar: Arg['foo'](help="Bar option"),
...         baz: Arg['foo'](help="Baz option")):
...     pass
>>> prog.setup_parser().print_help()
usage: prog [-h] bar baz
<BLANKLINE>
optional arguments:
  -h, --help  show this help message and exit
<BLANKLINE>
Foo:
  Foo group
<BLANKLINE>
  bar         Bar option
  baz         Baz option

类似地使用cli.mutually\u exclusivedecorator,参数可以 变成一个相互排斥的团体。

子命令

>>> @CLI("prog")
... @CLI.subparsers(help="sub-command help")
... class prog:
...     def __call__(foo: Flag('--foo', help="foo help")):
...         pass
...     def a(bar: Arg(type=int, help="bar help")):
...         """a help"""
...     def b(baz: Arg('--baz', choices='XYZ', help="baz help")):
...         """b help"""
>>> prog.parser.print_help()
usage: prog [-h] [--foo] {a,b} ...
<BLANKLINE>
positional arguments:
  {a,b}       sub-command help
    a         a help
    b         b help
<BLANKLINE>
optional arguments:
  -h, --help  show this help message and exit
  --foo       foo help
>>> prog.parser.parse_args(['a', '12'])
Namespace(_func=<function prog.a at 0x...>, _parser=..., bar=12, foo=False)
>>> prog.parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(_func=<function prog.b at 0x...>, _parser=..., baz='Z', foo=True)

可以在以下位置使用类定义生成更深层的子命令:

>>> @CLI("prog")
... class prog:
...     class foo:
...         """foo subcommand"""
...         def bar():
...             """foo bar subsubcommand"""
...         def baz():
...             """foo baz subsubcommand"""
...     class oof:
...         def rab():
...             """oof rab subsubcommand"""
...         def zab():
...             """oof zab subsubcommand"""
>>> prog.parser.print_help()
usage: prog [-h] {foo,oof} ...
<BLANKLINE>
positional arguments:
  {foo,oof}
    foo       foo subcommand
<BLANKLINE>
optional arguments:
  -h, --help  show this help message and exit

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
Java Webstart“javaws open”标志不适用于多个参数   java ArrayList声明和处理   获取数组中值的百分比(Java)   java将ArrayList转换为字符串以存储在共享首选项中   Java8Lambdas与泛型的结合使用   Scala数组到Java   如何使用java知道webcontainer的路径?   java使用“收集”和“合并”的组背后的算法是什么   java OSGi:在两个不同的包中具有相同的包路径   java混淆了swt画布。重画   java正则表达式,用于5位数逗号分隔的值,例如047000480004900   使用HttpClient显示非ASCI字符的java   水塔计算程序Java中球体体积的计算   java根据给定值调整框架中所有组件的大小   java Builder类中的其他方法(lombok注释)