當前位置: 首頁>>代碼示例>>Python>>正文


Python click.IntRange方法代碼示例

本文整理匯總了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 
開發者ID:autofitcloud,項目名稱:isitfit,代碼行數:20,代碼來源:cost.py

示例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 
開發者ID:SwissDataScienceCenter,項目名稱:renku-python,代碼行數:22,代碼來源:dataset.py

示例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) 
開發者ID:DataIntegrationAlliance,項目名稱:data_integration_celery,代碼行數:21,代碼來源:__init__.py

示例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 
開發者ID:guildai,項目名稱:guildai,代碼行數:20,代碼來源:server_support.py

示例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!") 
開發者ID:autofitcloud,項目名稱:isitfit,代碼行數:32,代碼來源:utils.py

示例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) 
開發者ID:mobiusklein,項目名稱:ms_deisotope,代碼行數:8,代碼來源:utils.py

示例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) 
開發者ID:cloudify-cosmo,項目名稱:cloudify-cli,代碼行數:14,代碼來源:cfy.py

示例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
    ) 
開發者ID:redcanari,項目名稱:canari3,代碼行數:11,代碼來源:question.py

示例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 
開發者ID:raiden-network,項目名稱:raiden-contracts,代碼行數:35,代碼來源:__main__.py

示例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']] 
開發者ID:qiime2,項目名稱:q2cli,代碼行數:35,代碼來源:util.py

示例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 
開發者ID:guildai,項目名稱:guildai,代碼行數:37,代碼來源:runs_list.py

示例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.)"
    ) 
開發者ID:ndbroadbent,項目名稱:icloud_photos_downloader,代碼行數:46,代碼來源:authentication.py

示例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),
    ) 
開發者ID:pokerregion,項目名稱:poker,代碼行數:47,代碼來源:commands.py

示例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 
開發者ID:venth,項目名稱:aws-adfs,代碼行數:51,代碼來源:role_chooser.py


注:本文中的click.IntRange方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。