当前位置: 首页>>代码示例>>Python>>正文


Python click.option方法代码示例

本文整理汇总了Python中click.option方法的典型用法代码示例。如果您正苦于以下问题:Python click.option方法的具体用法?Python click.option怎么用?Python click.option使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在click的用法示例。


在下文中一共展示了click.option方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_params

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def get_params(self, name):
        def show_help(ctx, param, value):
            if value and not ctx.resilient_parsing:
                click.echo(ctx.get_help(), color=ctx.color)
                ctx.exit()

        return [
            click.version_option(version=self.version, message="%(version)s"),
            click.option(
                "-h",
                "--help",
                is_flag=True,
                is_eager=True,
                expose_value=False,
                callback=show_help,
                help="Show this message and exit.",
            ),
        ] + self.common_options 
开发者ID:GaretJax,项目名称:django-click,代码行数:20,代码来源:adapter.py

示例2: load_config

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def load_config(func):
    """Decorator for add load config file option"""

    @functools.wraps(func)
    def internal(*args, **kwargs):
        filename = kwargs.pop('config')
        if filename is None:
            click.echo('--config option is required.', err=True)
            raise SystemExit(1)

        config = load(pathlib.Path(filename))
        kwargs['config'] = config
        return func(*args, **kwargs)

    decorator = click.option(
        '--config',
        '-c',
        type=click.Path(exists=True),
        envvar='YUI_CONFIG_FILE_PATH',
    )

    return decorator(internal) 
开发者ID:item4,项目名称:yui,代码行数:24,代码来源:cli.py

示例3: euler_options

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def euler_options(fn):
    """Decorator to link CLI options with their appropriate functions"""
    euler_functions = cheat, generate, preview, skip, verify, verify_all

    # Reverse functions to print help page options in alphabetical order
    for option in reversed(euler_functions):
        name, docstring = option.__name__, option.__doc__
        kwargs = {'flag_value': option, 'help': docstring}

        # Apply flag(s) depending on whether or not name is a single word
        flag = '--%s' % name.replace('_', '-')
        flags = [flag] if '_' in name else [flag, '-%s' % name[0]]

        fn = click.option('option', *flags, **kwargs)(fn)

    return fn 
开发者ID:iKevinY,项目名称:EulerPy,代码行数:18,代码来源:euler.py

示例4: analyze

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def analyze(
    context, api_client, api_key, input_file, output_file, output_format, verbose
):
    """Analyze the IP addresses in a log file, stdin, etc."""
    if input_file is None:
        if sys.stdin.isatty():
            output = [
                context.command.get_usage(context),
                (
                    "Error: at least one text file must be passed "
                    "either through the -i/--input_file option or through a shell pipe."
                ),
            ]
            click.echo("\n\n".join(output))
            context.exit(-1)
        else:
            input_file = click.open_file("-")
    if output_file is None:
        output_file = click.open_file("-", mode="w")

    result = api_client.analyze(input_file)
    return result 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:24,代码来源:subcommand.py

示例5: filter

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def filter(context, api_client, api_key, input_file, output_file, noise_only):
    """Filter the noise from a log file, stdin, etc."""
    if input_file is None:
        if sys.stdin.isatty():
            output = [
                context.command.get_usage(context),
                (
                    "Error: at least one text file must be passed "
                    "either through the -i/--input_file option or through a shell pipe."
                ),
            ]
            click.echo("\n\n".join(output))
            context.exit(-1)
        else:
            input_file = click.open_file("-")
    if output_file is None:
        output_file = click.open_file("-", mode="w")

    for chunk in api_client.filter(input_file, noise_only=noise_only):
        output_file.write(ANSI_MARKUP(chunk)) 
开发者ID:GreyNoise-Intelligence,项目名称:pygreynoise,代码行数:22,代码来源:subcommand.py

示例6: show_trace_option

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def show_trace_option(logging_mod=None, **kwargs):
    """A decorator that add --show_trace/-st option to decorated command"""

    if not isinstance(logging_mod, CustomLogging):
        raise TypeError("Logging object should be instance of CustomLogging.")

    names = ["--show_trace", "-st"]
    kwargs.setdefault("is_flag", True)
    kwargs.setdefault("default", False)
    kwargs.setdefault("expose_value", False)
    kwargs.setdefault("help", "Show the traceback for the exceptions")
    kwargs.setdefault("is_eager", True)

    def decorator(f):
        def _set_show_trace(ctx, param, value):
            if value:
                set_show_trace()

        return click.option(*names, callback=_set_show_trace, **kwargs)(f)

    return decorator 
开发者ID:nutanix,项目名称:calm-dsl,代码行数:23,代码来源:click_options.py

示例7: opt_exampleimg

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def opt_exampleimg(f):
    def callback(ctx, param, value):
        # Check if file qualifies alone
        if os.path.isfile(value):
            _value = value
        else:
            # Check if path relative to root qualifies
            _value = os.path.join(ctx.params['root'], value)
            if not os.path.isfile(_value):
                raise click.BadParameter('Cannot find example image '
                                         '"{f}"'.format(f=value))
            if not os.access(_value, os.R_OK):
                raise click.BadParameter('Found example image but cannot '
                                         'read from "{f}"'.format(f=_value))
        return os.path.abspath(_value)
    return click.option('--image', '-i',
                        default='example_img',
                        metavar='<image>',
                        show_default=True,
                        help='Example timeseries image',
                        callback=callback)(f) 
开发者ID:ceholden,项目名称:yatsm,代码行数:23,代码来源:options.py

示例8: opt_resultdir

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def opt_resultdir(f):
    def callback(ctx, param, value):
        # Check if path qualifies alone
        if os.path.isdir(value):
            _value = value
        else:
            # Check if path relative to root qualifies
            _value = os.path.join(ctx.params['root'], value)
            if not os.path.isdir(_value):
                raise click.BadParameter('Cannot find result directory '
                                         '"{d}"'.format(d=value))
        if not os.access(_value, os.R_OK):
            raise click.BadParameter('Found result directory but cannot '
                                     'read from "{d}"'.format(d=_value))
        return os.path.abspath(_value)
    return click.option('--result', '-r',
                        default='YATSM',
                        metavar='<directory>',
                        show_default=True,
                        help='Directory of results',
                        callback=callback)(f)


# CALLBACKS 
开发者ID:ceholden,项目名称:yatsm,代码行数:26,代码来源:options.py

示例9: replay

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def replay(
    cassette_path: str,
    id_: Optional[str],
    status: Optional[str] = None,
    uri: Optional[str] = None,
    method: Optional[str] = None,
) -> None:
    """Replay a cassette.

    Cassettes in VCR-compatible format can be replayed.
    For example, ones that are recorded with ``store-network-log`` option of `schemathesis run` command.
    """
    click.secho(f"{bold('Replaying cassette')}: {cassette_path}")
    with open(cassette_path) as fd:
        cassette = yaml.load(fd, Loader=SafeLoader)
    click.secho(f"{bold('Total interactions')}: {len(cassette['http_interactions'])}\n")
    for replayed in cassettes.replay(cassette, id_=id_, status=status, uri=uri, method=method):
        click.secho(f"  {bold('ID')}              : {replayed.interaction['id']}")
        click.secho(f"  {bold('URI')}             : {replayed.interaction['request']['uri']}")
        click.secho(f"  {bold('Old status code')} : {replayed.interaction['response']['status']['code']}")
        click.secho(f"  {bold('New status code')} : {replayed.response.status_code}\n") 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:23,代码来源:__init__.py

示例10: stop

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def stop(watson, at_):
    """
    Stop monitoring time for the current project.

    If `--at` option is given, the provided stopping time is used. The
    specified time must be after the beginning of the to-be-ended frame and must
    not be in the future.

    Example:

    \b
    $ watson stop --at 13:37
    Stopping project apollo11, started an hour ago and stopped 30 minutes ago. (id: e9ccd52) # noqa: E501
    """
    frame = watson.stop(stop_at=at_)
    output_str = u"Stopping project {}{}, started {} and stopped {}. (id: {})"
    click.echo(output_str.format(
        style('project', frame.project),
        (" " if frame.tags else "") + style('tags', frame.tags),
        style('time', frame.start.humanize()),
        style('time', frame.stop.humanize()),
        style('short_id', frame.id),
    ))
    watson.save() 
开发者ID:TailorDev,项目名称:Watson,代码行数:26,代码来源:cli.py

示例11: test_default_if_no_args

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def test_default_if_no_args():
    cli = DefaultGroup()

    @cli.command()
    @click.argument('foo', required=False)
    @click.option('--bar')
    def foobar(foo, bar):
        click.echo(foo)
        click.echo(bar)

    cli.set_default_command(foobar)
    assert r.invoke(cli, []).output.startswith('Usage:')
    assert r.invoke(cli, ['foo']).output == 'foo\n\n'
    assert r.invoke(cli, ['foo', '--bar', 'bar']).output == 'foo\nbar\n'
    cli.default_if_no_args = True
    assert r.invoke(cli, []).output == '\n\n' 
开发者ID:click-contrib,项目名称:click-default-group,代码行数:18,代码来源:test.py

示例12: _validate_options

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def _validate_options(self, options):
        result = {}
        for k, v in options.items():
            _k = k.upper()
            # process obsolete options
            if _k in self.RENAMED_OPTIONS:
                click.secho(
                    "Warning! `%s` option is deprecated and will be "
                    "removed in the next release! Please use "
                    "`%s` instead." % (
                        k, self.RENAMED_OPTIONS[_k].lower()),
                    fg="yellow"
                )
                k = self.RENAMED_OPTIONS[_k].lower()
            result[k] = v
        return result 
开发者ID:bq,项目名称:web2board,代码行数:18,代码来源:run.py

示例13: master

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def master(exp_str, exp_file, master_socket_path, log_dir):
    # Start the master
    assert (exp_str is None) != (exp_file is None), 'Must provide exp_str xor exp_file to the master'
    if exp_str:
        exp = json.loads(exp_str)
    elif exp_file:
        with open(exp_file, 'r') as f:
            exp = json.loads(f.read())
    else:
        assert False
    log_dir = os.path.expanduser(log_dir) if log_dir else '/tmp/es_master_{}'.format(os.getpid())
    mkdir_p(log_dir)
    run_master({'unix_socket_path': master_socket_path}, log_dir, exp)


# @cli.command()
# @click.option('--master_host', required=True)
# @click.option('--master_port', default=6379, type=int)
# @click.option('--relay_socket_path', required=True)
# @click.option('--num_workers', type=int, default=0) 
开发者ID:AdamStelmaszczyk,项目名称:learning2run,代码行数:22,代码来源:main.py

示例14: restore

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def restore(ctx, file: str, allow_nonempty: bool) -> None:
    cargs = ctx.obj['connargs']
    conn = cargs.new_connection()
    dbname = conn.dbname

    try:
        if not is_empty_db(conn) and not allow_nonempty:
            raise click.ClickException(
                f'cannot restore into the {dbname!r} database: '
                f'the database is not empty; '
                f'consider using the --allow-nonempty option'
            )

        restorer = restoremod.RestoreImpl()
        restorer.restore(conn, file)
    finally:
        conn.close() 
开发者ID:edgedb,项目名称:edgedb,代码行数:19,代码来源:__init__.py

示例15: check_status

# 需要导入模块: import click [as 别名]
# 或者: from click import option [as 别名]
def check_status(zap_helper, timeout):
    """
    Check if ZAP is running and able to receive API calls.

    You can provide a timeout option which is the amount of time in seconds
    the command should wait for ZAP to start if it is not currently running.
    This is useful to run before calling other commands if ZAP was started
    outside of zap-cli. For example:

        zap-cli status -t 60 && zap-cli open-url "http://127.0.0.1/"

    Exits with code 1 if ZAP is either not running or the command timed out
    waiting for ZAP to start.
    """
    with helpers.zap_error_handler():
        if zap_helper.is_running():
            console.info('ZAP is running')
        elif timeout is not None:
            zap_helper.wait_for_zap(timeout)
            console.info('ZAP is running')
        else:
            console.error('ZAP is not running')
            sys.exit(2) 
开发者ID:Grunny,项目名称:zap-cli,代码行数:25,代码来源:cli.py


注:本文中的click.option方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。