推荐学习书目
› 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 · Jun 14, 2020 · 2400 views
    This topic created in 2301 days ago, the information mentioned may be changed or developed.
    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 replies  •  2020-06-14 15:40:54 +08:00
    ipwx
        1
    ipwx  
       Jun 14, 2020
    写个自定义的 decorator,包装一下你的 child command,把传进来的通用参数都处理好,再丢给子命令。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   755 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 21:32 · PVG 05:32 · LAX 14:32 · JFK 17:32
    ♥ Do have faith in what you're doing.