本文整理汇总了Python中click.IntRange方法的典型用法代码示例。如果您正苦于以下问题:Python click.IntRange方法的具体用法?Python click.IntRange怎么用?Python click.IntRange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类click
的用法示例。
在下文中一共展示了click.IntRange方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cost
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def cost(ctx, filter_region, ndays, profile):
# FIXME click bug: `isitfit command subcommand --help` is calling the code in here. Workaround is to check --help and skip the whole section
import sys
if '--help' in sys.argv: return
# gather anonymous usage statistics
ping_matomo("/cost?filter_region=%s&ndays=%i"%(filter_region, ndays))
# save to click context
ctx.obj['ndays'] = ndays
ctx.obj['filter_region'] = filter_region
pass
# Check note above about ndays
# Another note about ndays: using click.IntRange for validation. Ref: https://click.palletsprojects.com/en/7.x/options/?highlight=prompt#range-options
示例2: prompt_tag_selection
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def prompt_tag_selection(tags):
"""Prompt user to chose a tag or <HEAD>."""
# Prompt user to select a tag to export
tags = sorted(tags, key=lambda t: t.created)
text_prompt = 'Tag to export: \n\n<HEAD>\t[1]\n'
text_prompt += '\n'.join(
'{}\t[{}]'.format(t.name, i) for i, t in enumerate(tags, start=2)
)
text_prompt += '\n\nTag'
selection = click.prompt(
text_prompt, type=click.IntRange(1,
len(tags) + 1), default=1
)
if selection > 1:
return tags[selection - 2]
return None
示例3: main
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def main():
promt_str = '0) 退出 '
promt_str += ' '.join(['%d) %s' % (num, _[1]) for num, _ in enumerate(func_list, start=1)])
@click.command()
@click.option('--num', type=click.IntRange(0, len(func_list)), prompt=promt_str)
def task_choose(num, **kwargs):
if num is None:
logger.error('输入 num 参数无效')
return False
elif num == 0:
return True
else:
func_list[num - 1][0]()
return False
finished = False
while not finished:
finished = task_choose(standalone_mode=False)
示例4: host_and_port_options
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def host_and_port_options(fn):
click_util.append_params(
fn,
[
click.Option(
("-h", "--host",),
metavar="HOST",
help="Name of host interface to listen on.",
),
click.Option(
("-p", "--port",),
metavar="PORT",
help="Port to listen on.",
type=click.IntRange(0, 65535),
),
],
)
return fn
示例5: ask_feedback
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def ask_feedback():
# TODO should use a proper feedback gathering method rather than collecting it in matomo
# but this is a shortcut for now
print("")
import click
a1 = click.prompt("How useful was this? (0: wtf, 1: useless, 2: IDK, 3: kind of, 4: epiphanic)", type=click.IntRange(0, 4))
ping_matomo("/feedback?a1_usefulness=%i"%a1)
q2 = {
0: "Seriously? Why?",
1: "Is there no hope? What can be done?",
2: "What would make things clearer?",
3: "What can we improve?",
4: "TBH, I wasn't expecting this. Really? Why?"
}
a2 = click.prompt(q2[a1])
ping_matomo("/feedback?a2_why=%s"%a2)
a3a = click.confirm("Shall we schedule a 10-minute phone call?")
ping_matomo("/feedback?a3a_can_we_call=%s"%b2l(a3a))
a3b = None
a3c = None
if a3a:
a3b = click.prompt("Phone number with country code")
ping_matomo("/feedback?a3b_phone=%s"%a3b)
a3c = click.prompt("Best time to call (include timezone)")
ping_matomo("/feedback?a3c_time=%s"%a3c)
print("Perfect! In the mean time, feel free to reach me at shadi@autofitcloud.com")
else:
print("Ok. You can always reach me at shadi@autofitcloud.com")
print("Thanks!")
示例6: processes_option
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def processes_option(f):
opt = click.option(
"-p", "--processes", 'processes', type=click.IntRange(1, multiprocessing.cpu_count()),
default=min(multiprocessing.cpu_count(), 4), help=('Number of worker processes to use. Defaults to 4 '
'or the number of CPUs, whichever is lower'))
return opt(f)
示例7: keep_last
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def keep_last(resource_name,
required=False,
mutually_exclusive_with=None):
kwargs = {
'required': required,
'type': click.IntRange(min=1),
'help': helptexts.KEEP_LAST.format(resource_name),
}
if mutually_exclusive_with:
kwargs['cls'] = MutuallyExclusiveOption
kwargs['mutually_exclusive'] = mutually_exclusive_with
return click.option('--keep-last', **kwargs)
示例8: prompt_menu
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def prompt_menu(question, choices, default=0, **kwargs):
if len(choices) == 1:
return 0
return click.prompt(
'{}\n{}'.format('\n'.join('[%d] - %s' % (i, c) for i, c in enumerate(choices)), question),
default=default,
type=click.IntRange(0, len(choices) - 1),
**kwargs
)
示例9: common_options
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def common_options(func: Callable) -> Callable:
"""A decorator that combines commonly appearing @click.option decorators."""
@click.option("--private-key", required=True, help="Path to a private key store.")
@click.option(
"--password-file",
help="Text file containing the password for the provided account",
default=None,
type=click.Path(exists=True, dir_okay=False),
show_default=True,
callback=lambda ctx, param, value: Path(value) if value is not None else None,
)
@click.option(
"--rpc-provider",
default="http://127.0.0.1:8545",
help="Address of the Ethereum RPC provider",
)
@click.option("--wait", default=300, help="Max tx wait time in s.")
@click.option("--gas-price", default=5, type=IntRange(min=1), help="Gas price to use in gwei")
@click.option("--gas-limit", default=5_500_000)
@click.option(
"--contracts-version",
default=None,
help="Contracts version to verify. Current version will be used by default.",
)
@functools.wraps(func)
def wrapper(*args: List, **kwargs: Dict) -> Any:
return func(*args, **kwargs)
return wrapper
# pylint: disable=R0913
示例10: convert_primitive
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def convert_primitive(ast):
import click
mapping = {
'Int': int,
'Str': str,
'Float': float,
'Color': str,
'Bool': bool
}
# TODO: it would be a good idea to refactor this someday, but until then
# just handle the few predicates we know about.
predicate = ast['predicate']
if predicate:
if predicate['name'] == 'Choices' and ast['name'] == 'Str':
return click.Choice(predicate['choices'])
elif predicate['name'] == 'Range' and ast['name'] == 'Int':
start = predicate['range'][0]
end = predicate['range'][1]
# click.IntRange is always inclusive
if start is not None and not predicate['inclusive'][0]:
start += 1
if end is not None and not predicate['inclusive'][1]:
end -= 1
return click.IntRange(start, end)
elif predicate['name'] == 'Range' and ast['name'] == 'Float':
# click.FloatRange will be in click 7.0, so for now the
# range handling will just fallback to qiime2.
return mapping['Float']
else:
raise NotImplementedError()
else:
return mapping[ast['name']]
示例11: runs_list_options
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def runs_list_options(fn):
click_util.append_params(
fn,
[
click.Option(
("-a", "--all"),
help="Show all runs (by default only the last 20 runs are shown).",
is_flag=True,
),
click.Option(
("-m", "--more"),
help=("Show 20 more runs. Maybe used multiple times."),
count=True,
),
click.Option(
("-n", "--limit"),
metavar="N",
type=click.IntRange(min=1),
help="Limit number of runs shown.",
),
click.Option(("-d", "--deleted"), help="Show deleted runs.", is_flag=True),
click.Option(
("-A", "--archive",), metavar="DIR", help="Show archived runs in DIR."
),
runs_support.all_filters,
click.Option(("--json",), help="Format runs as JSON.", is_flag=True),
click.Option(("-v", "--verbose"), help="Show run details.", is_flag=True),
click.Option(
("-r", "--remote",),
metavar="REMOTE",
help="List runs on REMOTE rather than local runs.",
),
],
)
return fn
示例12: request_2sa
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def request_2sa(icloud, logger):
"""Request two-step authentication. Prompts for SMS or device"""
devices = icloud.trusted_devices
devices_count = len(devices)
device_index = 0
if devices_count > 0:
for i, device in enumerate(devices):
print(
" %s: %s" %
(i, device.get(
"deviceName", "SMS to %s" %
device.get("phoneNumber"))))
# pylint: disable-msg=superfluous-parens
print(" %s: Enter two-factor authentication code" % devices_count)
# pylint: enable-msg=superfluous-parens
device_index = click.prompt(
"Please choose an option:",
default=0,
type=click.IntRange(
0,
devices_count))
if device_index == devices_count:
# We're using the 2FA code that was automatically sent to the user's device,
# so can just use an empty dict()
device = dict()
else:
device = devices[device_index]
if not icloud.send_verification_code(device):
logger.error("Failed to send two-factor authentication code")
sys.exit(1)
code = click.prompt("Please enter two-factor authentication code")
if not icloud.validate_verification_code(device, code):
logger.error("Failed to verify two-factor authentication code")
sys.exit(1)
logger.info(
"Great, you're all set up. The script can now be run without "
"user interaction until 2SA expires.\n"
"You can set up email notifications for when "
"the two-step authentication expires.\n"
"(Use --help to view information about SMTP options.)"
)
示例13: twoplustwo_player
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import (
ForumMember,
AmbiguousUserNameError,
UserNotFoundError,
)
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickException('User "%s" not found!' % username)
except AmbiguousUserNameError as e:
click.echo("Got multiple users with similar names!", err=True)
for ind, user in enumerate(e.users):
click.echo(f"{ind + 1}. {user.name}", err=True)
number = click.prompt(
f"Which would you like to see [1-{len(e.users)}]",
prompt_suffix="? ",
type=click.IntRange(1, len(e.users)),
err=True,
)
userid = e.users[int(number) - 1].id
member = ForumMember.from_userid(userid)
click.echo(err=True) # empty line after input
_print_header("Two plus two forum member")
_print_values(
("Username", member.username),
("Forum id", member.id),
("Location", member.location),
("Total posts", member.total_posts),
("Posts per day", member.posts_per_day),
("Rank", member.rank),
("Last activity", member.last_activity),
("Join date", member.join_date),
("Usergroups", member.public_usergroups),
("Profile picture", member.profile_picture),
("Avatar", member.avatar),
)
示例14: choose_role_to_assume
# 需要导入模块: import click [as 别名]
# 或者: from click import IntRange [as 别名]
def choose_role_to_assume(config, principal_roles):
chosen_principal_arn = None
chosen_role_arn = None
principal_roles_emptied = not bool(principal_roles)
if principal_roles_emptied:
return chosen_principal_arn, chosen_role_arn
role_collection = []
principal_roles = collections.OrderedDict(sorted(principal_roles.items(), key=lambda t: t[0]))
for account_name in principal_roles.keys():
roles = principal_roles[account_name]
for role_arn in roles.keys():
role_collection.append([roles[role_arn]['principal_arn'], role_arn])
logging.debug(u'Role arn from config: {}'.format(config.role_arn))
chosen_principal_role = [role for role in role_collection if config.role_arn == role[1]]
logging.debug(u'Calculated role collection: {}'.format(role_collection))
if len(chosen_principal_role) == 1:
logging.debug(u'Chosen principal role based on previously used role_arn stored in config: {}'
.format(chosen_principal_role))
chosen_principal_arn = chosen_principal_role[0][0]
chosen_role_arn = chosen_principal_role[0][1]
return chosen_principal_arn, chosen_role_arn
if len(role_collection) == 1:
logging.debug(u'There is only one role to choose')
chosen_principal_arn = role_collection[0][0]
chosen_role_arn = role_collection[0][1]
elif len(role_collection) > 1:
logging.debug(u'Manual choice')
click.echo(u'Please choose the role you would like to assume:')
i = 0
for account_name in principal_roles.keys():
roles = principal_roles[account_name]
click.echo('{}:'.format(account_name))
for role_arn in roles.keys():
role_entry = roles[role_arn]
click.echo(' [ {} -> {} ]: {}'.format(role_entry['name'].ljust(30, ' ' if i % 2 == 0 else '.'), i, role_arn))
i += 1
selected_index = click.prompt(text='Selection', type=click.IntRange(0, len(role_collection)))
chosen_principal_arn = role_collection[selected_index][0]
chosen_role_arn = role_collection[selected_index][1]
return chosen_principal_arn, chosen_role_arn