Python CLI开发

click

组嵌套和分割

参考: [How can I split my Click commands, each with a set of sub-commands, into multiple files?](https://stackoverflow.com/questions/34643620/how-can-i-split-my-click-commands-each-with-a-set-of-sub-commands-into-multipl)

project/
├── __init__.py
├── init.py
└── commands
    ├── __init__.py
    └── cloudflare.py

最外层

import click
from .commands.cloudflare import cloudflare


@click.group()
def cli():
    pass


cli.add_command(cloudflare)

其中一个组

import click


@click.group()
def cloudflare():
    pass


@cloudflare.command()
def zone():
    click.echo('This is the zone subcommand of the cloudflare command')

argparse

问题

  1. nargs=argparse.REMAINDER

    • “All the remaining command-line arguments are gathered into a list”

    • 不能用来收集子parser中的剩余arguments:

      • 用在父parser add_subparsers前(想将父parser的选项直接传递给其他程序处理),子parser的解析会出问题;用在父parser添加所有子parser后,并不能收集处于父parser和子parser之间的options

      • 详见:https://stackoverflow.com/a/43219281

        而且所有以---开头的arguments都会先被识别为options,而argparse.REMAINDER在这之后起作用,也就是说,argparse.REMAINDER无法收集它应当收集的-x--xxx,除非在-x--xxx之前添加--(表示options结束),此时其收集的list为['--', '-x','--xxx']

    • 可以parse_known_args()

      • 虽然,” Prefix matching rules apply to parse_known_args(). The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.“
      • 但是不会将子parser后选项同父parser的匹配
  2. namespace中父parser的arguments会和子parser的混合在一起

    • 想在父parser add_subparsers前调用parse_known_args()对父parse的arguments解析一下,但这样会影响子命令的解析
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值