本文整理匯總了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
示例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)
示例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
示例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
示例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))
示例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
示例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)
示例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
示例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")
示例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()
示例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'
示例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
示例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)
示例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()
示例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)