本文整理汇总了Python中click.get_current_context方法的典型用法代码示例。如果您正苦于以下问题:Python click.get_current_context方法的具体用法?Python click.get_current_context怎么用?Python click.get_current_context使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类click
的用法示例。
在下文中一共展示了click.get_current_context方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def execute(self, *args, **kwargs):
"""
Called when run through `call_command`. `args` are passed through,
while `kwargs` is the __dict__ of the return value of
`self.create_parser('', name)` updated with the kwargs passed to
`call_command`.
"""
# Remove internal Django command handling machinery
kwargs.pop("skip_checks", None)
parent_ctx = click.get_current_context(silent=True)
with self.make_context("", list(args), parent=parent_ctx) as ctx:
# Rename kwargs to to the appropriate destination argument name
opt_mapping = dict(self.map_names())
arg_options = {
opt_mapping.get(key, key): value for key, value in six.iteritems(kwargs)
}
# Update the context with the passed (renamed) kwargs
ctx.params.update(arg_options)
# Invoke the command
self.invoke(ctx)
示例2: calmrepl
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def calmrepl():
"""Enable an interactive prompt shell
> :help
REPL help:
External Commands:
prefix external commands with "!"
Internal Commands:
prefix internal commands with ":"
:exit, :q, :quit exits the repl
:?, :h, :help displays general help information
"""
repl(click.get_current_context())
示例3: style_tweet
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def style_tweet(tweet, porcelain=False):
conf = click.get_current_context().obj["conf"]
limit = conf.character_limit
if porcelain:
return "{nick}\t{url}\t{tweet}".format(
nick=tweet.source.nick,
url=tweet.source.url,
tweet=str(tweet))
else:
if sys.stdout.isatty() and not tweet.text.isprintable():
return None
styled_text = format_mentions(tweet.text)
len_styling = len(styled_text) - len(click.unstyle(styled_text))
final_text = textwrap.shorten(styled_text, limit + len_styling) if limit else styled_text
timestamp = tweet.absolute_datetime if conf.use_abs_time else tweet.relative_datetime
return "➤ {nick} ({time}):\n{tweet}".format(
nick=click.style(tweet.source.nick, bold=True),
tweet=final_text,
time=click.style(timestamp, dim=True))
示例4: validate_text
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def validate_text(ctx, param, value):
conf = click.get_current_context().obj["conf"]
if isinstance(value, tuple):
value = " ".join(value)
if not value and not sys.stdin.isatty():
value = click.get_text_stream("stdin").read()
if value:
value = value.strip()
if conf.character_warning and len(value) > conf.character_warning:
click.confirm("✂ Warning: Tweet is longer than {0} characters. Are you sure?".format(
conf.character_warning), abort=True)
return value
else:
raise click.BadArgumentUsage("Text can’t be empty.")
示例5: register
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def register(cfg, location, kernel):
first_run(cfg)
kernel_version = kernel
if kernel_version == 'latest':
templates = local.get_local_templates(pros_cfg=cfg.pros_cfg,
template_types=[TemplateTypes.kernel]) # type: List[Identifier]
if not templates or len(templates) == 0:
click.echo('No templates have been downloaded! Use `pros conduct download` to download the latest kernel or'
' specify a kernel manually.')
click.get_current_context().abort()
sys.exit()
kernel_version = sorted(templates, key=lambda t: semver.Version(t.version))[-1].version
proscli.utils.debug('Resolved version {} to {}'.format(kernel, kernel_version))
cfg = prosconfig.ProjectConfig(location, create=True, raise_on_error=True)
cfg.kernel = kernel_version
if not location:
click.echo('Location not specified, registering current directory.')
click.echo('Registering {} with kernel {}'.format(location or os.path.abspath('.'), kernel_version))
cfg.save()
# endregion
示例6: terminal
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def terminal(port):
click.echo(click.style('NOTE: This is an early prototype of the terminal.'
' Nothing is guaranteed to work.', bold=True))
if port == 'default':
if len(prosflasher.ports.list_com_ports()) == 1:
port = prosflasher.ports.list_com_ports()[0].device
elif len(prosflasher.ports.list_com_ports()) > 1:
click.echo('Multiple ports were found:')
click.echo(prosflasher.ports.create_port_list())
port = click.prompt('Select a port to open',
type=click.Choice([p.device for p in prosflasher.ports.list_com_ports()]))
else:
click.echo('No ports were found.')
click.get_current_context().abort()
sys.exit()
ser = prosflasher.ports.create_serial(port, serial.PARITY_NONE)
term = proscli.serial_terminal.Terminal(ser)
signal.signal(signal.SIGINT, term.stop)
term.start()
while term.alive:
time.sleep(0.005)
term.join()
ser.close()
print('Exited successfully')
sys.exit(0)
示例7: _notify
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def _notify(p, **data):
"""The callback func that will be hooked to the ``notify`` command"""
message = data.get("message")
if not message and not sys.stdin.isatty():
message = click.get_text_stream("stdin").read()
data["message"] = message
data = clean_data(data)
ctx = click.get_current_context()
if ctx.obj.get("env_prefix"):
data["env_prefix"] = ctx.obj["env_prefix"]
rsp = p.notify(**data)
rsp.raise_on_errors()
click.secho(f"Succesfully sent a notification to {p.name}!", fg="green")
示例8: citations
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def citations(path):
import qiime2.sdk
import io
from q2cli.core.config import CONFIG
ctx = click.get_current_context()
try:
result = qiime2.sdk.Result.load(path)
except Exception as e:
header = 'There was a problem loading %s as a QIIME 2 result:' % path
q2cli.util.exit_with_error(e, header=header)
if result.citations:
with io.StringIO() as fh:
result.citations.save(fh)
click.echo(fh.getvalue(), nl=False)
ctx.exit(0)
else:
click.echo(CONFIG.cfg_style('problem', 'No citations found.'),
err=True)
ctx.exit(1)
示例9: autoactivate
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def autoactivate(client, endpoint_id, if_expires_in=None):
"""
Attempts to auto-activate the given endpoint with the given client
If auto-activation fails, parses the returned activation requirements
to determine which methods of activation are supported, then tells
the user to use 'globus endpoint activate' with the correct options(s)
"""
kwargs = {}
if if_expires_in is not None:
kwargs["if_expires_in"] = if_expires_in
res = client.endpoint_autoactivate(endpoint_id, **kwargs)
if res["code"] == "AutoActivationFailed":
message = (
"The endpoint could not be auto-activated and must be "
"activated before it can be used.\n\n"
+ activation_requirements_help_text(res, endpoint_id)
)
click.echo(message, err=True)
click.get_current_context().exit(1)
else:
return res
示例10: print_unix_response
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def print_unix_response(res):
res = _jmespath_preprocess(res)
try:
unix_formatted_print(res)
# Attr errors indicate that we got data which cannot be unix formatted
# likely a scalar + non-scalar in an array, though there may be other cases
# print good error and exit(2) (Count this as UsageError!)
except AttributeError:
click.echo(
"UNIX formatting of output failed."
"\n "
"This usually means that data has a structure which cannot be "
"handled by the UNIX formatter."
"\n "
"To avoid this error in the future, ensure that you query the "
'exact properties you want from output data with "--jmespath"',
err=True,
)
click.get_current_context().exit(2)
示例11: main
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def main(**parsed_settings):
click_context = click.get_current_context()
click_context.color = True # GitLab doesn't report terminal type correctly so we need to force it
settings.update(parsed_settings)
rancher.session.auth = settings['access_key'], settings['secret_key']
try:
deployment.load_from_settings(settings)
except UpgradeFailed:
sys.exit(1) # we handled it gracefully already
hooks.dispatch('before_upgrade')
try:
upgrade(deployment.services)
except Exception as ex:
hooks.dispatch('after_upgrade_failure')
if isinstance(ex, UpgradeFailed):
sys.exit(1) # we handled it gracefully already
raise
else:
hooks.dispatch('after_upgrade_success')
示例12: pass_verbosity
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def pass_verbosity(f):
"""
Marks a callback as wanting to receive the verbosity as a keyword argument.
"""
def new_func(*args, **kwargs):
kwargs["verbosity"] = click.get_current_context().verbosity
return f(*args, **kwargs)
return update_wrapper(new_func, f)
示例13: echo_result
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def echo_result(function):
"""Decorator that prints subcommand results correctly formatted.
:param function: Subcommand that returns a result from the API.
:type function: callable
:returns: Wrapped function that prints subcommand results
:rtype: callable
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
context = click.get_current_context()
params = context.params
output_format = params["output_format"]
formatter = FORMATTERS[output_format]
if isinstance(formatter, dict):
# For the text formatter, there's a separate formatter for each subcommand
formatter = formatter[context.command.name]
output = formatter(result, params.get("verbose", False)).strip("\n")
click.echo(
output, file=params.get("output_file", click.open_file("-", mode="w"))
)
return wrapper
示例14: handle_exceptions
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def handle_exceptions(function):
"""Print error and exit on API client exception.
:param function: Subcommand that returns a result from the API.
:type function: callable
:returns: Wrapped function that prints subcommand results
:rtype: callable
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except RequestFailure as exception:
body = exception.args[1]
error_message = "API error: {}".format(body["error"])
LOGGER.error(error_message)
click.echo(error_message)
click.get_current_context().exit(-1)
except RequestException as exception:
error_message = "API error: {}".format(exception)
LOGGER.error(error_message)
click.echo(error_message)
click.get_current_context().exit(-1)
return wrapper
示例15: pass_api_client
# 需要导入模块: import click [as 别名]
# 或者: from click import get_current_context [as 别名]
def pass_api_client(function):
"""Create API client form API key and pass it to subcommand.
:param function: Subcommand that returns a result from the API.
:type function: callable
:returns: Wrapped function that prints subcommand results
:rtype: callable
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
context = click.get_current_context()
api_key = context.params.get("api_key")
config = load_config()
if api_key is None:
if not config["api_key"]:
prog_name = context.parent.info_name
click.echo(
"\nError: API key not found.\n\n"
"To fix this problem, please use any of the following methods "
"(in order of precedence):\n"
"- Pass it using the -k/--api-key option.\n"
"- Set it in the GREYNOISE_API_KEY environment variable.\n"
"- Run {!r} to save it to the configuration file.\n".format(
"{} setup".format(prog_name)
)
)
context.exit(-1)
api_key = config["api_key"]
api_client = GreyNoise(
api_key=api_key, timeout=config["timeout"], integration_name="cli"
)
return function(api_client, *args, **kwargs)
return wrapper