V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fangwenxue
V2EX  ›  Python

Python click 子命令怎么共用父级选项

  •  
  •   fangwenxue · 2020-06-14 14:52:19 +08:00 · 1486 次点击
    这是一个创建于 1405 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import logging
    
    import click
    
    DEFAULT_FORMATTER = '%(asctime)s[%(filename)s:%(lineno)d][%(levelname)s]:%(message)s'
    logging.basicConfig(format=DEFAULT_FORMATTER, level=logging.INFO)
    
    
    @click.group(invoke_without_command=True)
    @click.option('--limit', type=int, default=5)
    @click.option('--chunk-size', type=int, default=5)
    @click.option('-vvv', is_flag=True)
    @click.option('--debug', envvar='DEBUG', default=False, help='debug mode')
    @click.pass_context
    def cli(ctx, **kwargs):
        if kwargs.get('debug'):
            logging.basicConfig(format=DEFAULT_FORMATTER, level=logging.DEBUG)
    
        ctx.obj = kwargs
        if ctx.invoked_subcommand is None:
            ctx.invoke('index')
    
    
    @cli.command()
    @click.option('-a')
    @click.pass_context
    def index(ctx, **kwargs):
        kwargs.update(ctx.obj)
        print(kwargs)
    
    
    @cli.command()
    @click.option('-b')
    @click.pass_context
    def test(ctx, **kwargs):
        kwargs.update(ctx.obj)
        print(kwargs)
    
    
    if __name__ == '__main__':
        cli()
        
        
    python3 test.py -vvv test 这样是可以的
    
    python3 test.py test -vvv 
    
    这样提示找不到选项
    怎样支持这种命令
    
    
    1 条回复    2020-06-14 15:40:54 +08:00
    ipwx
        1
    ipwx  
       2020-06-14 15:40:54 +08:00
    写个自定义的 decorator,包装一下你的 child command,把传进来的通用参数都处理好,再丢给子命令。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2602 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:24 · PVG 12:24 · LAX 21:24 · JFK 00:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.