通过上下文传递类实例

时间:2017-10-03 17:49:21

标签: python python-2.7 python-click

所以我只是尝试在click和repo中使用对象和类,这只是我从他们的示例列表中获取的一个示例。

当我尝试执行最小的代码集时,调用函数时会抛出错误,如下所示:

#!/usr/bin/env python

import os
import click

class Repo(object):

    def __init__(self, home):
        self.home = home
        self.config = {}
        self.verbose = False

    def set_config(self, key, value):
        self.config[key] = value
        if self.verbose:
            click.echo('  config[%s] = %s' % (key, value), file=sys.stderr)

    def __repr__(self):
        return '<Repo %r>' % self.home
pass_repo = click.make_pass_decorator(Repo)

@click.group()
@click.option('--repo-home', envvar='REPO_HOME', default='.repo',
              metavar='PATH', help='Changes the repository folder location.')
@click.option('--config', nargs=2, multiple=True,
              metavar='KEY VALUE', help='Overrides a config key/value pair.')
@click.option('--verbose', '-v', is_flag=True,
              help='Enables verbose mode.')

@click.pass_context
def cli(ctx, repo_home, config, verbose):
    """Repo is a command line tool that showcases how to build complex
    command line interfaces with Click.
    This tool is supposed to look like a distributed version control
    system to show how something like this can be structured.
    """
    # Create a repo object and remember it as as the context object.  From
    # this point onwards other commands can refer to it by using the
    # @pass_repo decorator.
    click.echo('Hello world')
    click.echo('Hello %s!' % repo_home)
    ctx.obj = Repo(os.path.abspath(repo_home))
    ctx.obj.verbose = verbose
    for key, value in config:
        ctx.obj.set_config(key, value)

@cli.command()
@pass_repo
def clone(repo):
    """Clones a repository.
    This will clone the repository at SRC into the folder DEST.  If DEST
    is not provided this will automatically use the last path component
    of SRC and create that folder.
    """
    click.echo('Making shallow checkout')

if __name__ == '__main__':
    clone()

命令:

python click_test.py

错误:

  

RuntimeError:管理以在没有“Repo”现有

类型的上下文对象的情况下调用回调

我不确定我是否需要cli功能和克隆功能?我可以在cli中创建一个对象并初始化repo类吗?

1 个答案:

答案 0 :(得分:0)

您的代码调用clone()函数,该函数不是顶级函数。您需要调用cli()这是一个较小的示例,显示如何在上下文中传递类实例。

示例代码:

import click

class SampleClass(object):

    def __init__(self, some_info):
        self.some_info = some_info


pass_class = click.make_pass_decorator(SampleClass)


@click.group()
@click.pass_context
def cli(ctx):
    ctx.obj = SampleClass('Something to Store in Class')

@cli.command()
@pass_class
def a_command(a_class_instance):
    click.echo("Here we have access to Class instance from Context")
    click.echo("It contains '{}'".format(a_class_instance.some_info))


if __name__ == '__main__':
    cli(['a_command'])

结果:

Here we have access to Class instance from Context
It contains 'Something to Store in Class'