Python click 模块,unstyle() 实例源码

我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用click.unstyle()

项目:kubey    作者:bradrf    | 项目源码 | 文件源码
def webui(obj):
    '''List dashboard links for matching pods (if only one matched, URL is opened in browser).'''
    kubectl = obj.kubey.kubectl
    info = click.unstyle(kubectl.call_capture('cluster-info'))
    dash_endpoint = re.search(r'kubernetes-dashboard.*?(http\S+)', info).group(1)
    urls = []
    for pod in obj.kubey.each_pod(obj.maximum):
        pod_path = '/#/pod/{0}/{1}?namespace={0}'.format(pod.namespace, pod.name)
        urls.append(dash_endpoint + pod_path)
    if len(urls) == 1:
        url = urls[0]
        click.echo(url)
        click.launch(url)
    else:
        for url in urls:
            click.echo(url)
项目:dj    作者:aleontiev    | 项目源码 | 文件源码
def init(name, runtime):
    """Create a new Django app."""
    runtime = click.unstyle(runtime)

    stdout.write(
        style.format_command(
            'Initializing',
            '%s %s %s' % (name, style.gray('@'), style.green(runtime))
        )
    )

    config = Config(os.getcwd())
    config.set('runtime', runtime)
    config.save()

    generate.main(['init', name], standalone_mode=False)
    run.main(['python', 'manage.py', 'migrate'])
项目:twtxt    作者:buckket    | 项目源码 | 文件源码
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))
项目:twtxt    作者:buckket    | 项目源码 | 文件源码
def parse_tweet(raw_tweet, source, now=None):
    """
        Parses a single raw tweet line from a twtxt file
        and returns a :class:`Tweet` object.

        :param str raw_tweet: a single raw tweet line
        :param Source source: the source of the given tweet
        :param Datetime now: the current datetime

        :returns: the parsed tweet
        :rtype: Tweet
    """
    if now is None:
        now = datetime.now(timezone.utc)

    raw_created_at, text = raw_tweet.split("\t", 1)
    created_at = parse_iso8601(raw_created_at)

    if created_at > now:
        raise ValueError("Tweet is from the future")

    return Tweet(click.unstyle(text.strip()), created_at, source)
项目:cv.soulshake.net    作者:soulshake    | 项目源码 | 文件源码
def intro():
    intro = [
        click.style(".", dim=True),
        "Hi, I'm {}.".format(click.style("AJ", fg='red')),
        "I'm a {} with a strong interest in ".format(click.style("Python developer", fg='yellow')),
        "APIs, CLIs and subverting the dominant paradigm.",
        "This is my resume.",
        "",
        "Note: this is primarily intended for command-line addicts.",
        "A more conventional version can be found on LinkedIn."
        ]
    intro = [click.unstyle(item).center(80) for item in intro]
    intro = "\n".join(intro)
    intro = intro.replace("APIs", click.style("APIs", fg='green'))
    intro = intro.replace("CLIs", click.style("CLIs", fg='blue'))
    intro = intro.replace("subverting the dominant paradigm",
                          click.style("subverting the dominant paradigm",
                                      fg='magenta'))

    colSpan = 5
    rowSpan = 3.5

    ret = Markdown(data=intro, colSpan=colSpan, rowSpan=rowSpan, label="")
    return ret
项目:dj    作者:aleontiev    | 项目源码 | 文件源码
def get_context(name, description, author, email, version, django_version):
    name = click.unstyle(name)
    description = click.unstyle(description)
    email = click.unstyle(email)
    author = click.unstyle(author)
    version = click.unstyle(version)
    django_version = click.unstyle(django_version)
    return {
        'app': inflection.underscore(name),
        'description': description,
        'author': author,
        'email': email,
        'version': version,
        'django_version': django_version
    }
项目:two1-python    作者:21dotco    | 项目源码 | 文件源码
def _inbox(config, client):
    """Show a list of notifications on a click pager.

    Args:
        config (Config): config object used for getting .two1 information
        client (two1.server.rest_client.TwentyOneRestClient) an object for
            sending authenticated requests to the TwentyOne backend.

    Returns:
        list: list of notifications in users inbox
    """
    prints = []

    notifications, has_unreads = get_notifications(config, client)
    if not notifications:
        logger.info("Inbox empty")
        return notifications

    if len(notifications) > 0:
        prints.append(uxstring.UxString.notification_intro)
        prints.extend(notifications)

    output = "\n".join(prints)
    logger.info(output, pager=True)

    if has_unreads:
        client.mark_notifications_read(config.username)

    return tuple(map(click.unstyle, notifications))
项目:two1-python    作者:21dotco    | 项目源码 | 文件源码
def log(ctx, debug):
    """View a log of events of earning/spending BTC."""
    prints = []

    logs = get_bc_logs(ctx.obj['client'], debug)
    prints.extend(logs)

    output = "\n".join(prints)
    logger.info(output, pager=True)

    return tuple(map(click.unstyle, logs))
项目:ldap3-cli    作者:cannatag    | 项目源码 | 文件源码
def ljust_style(string, col, styles, lengths, fill=' '):
    if not string:
        string = ''
    length = lengths[col]
    unstyled = click.unstyle(string)
    if len(unstyled) == len(string): # not already styled
        if styles:
            if col >= len(styles):
                string = apply_style(styles[:-1], string)  # apply last style for remaining fields
            else:
                string = apply_style(styles[col], string)
    if len(unstyled) < length:
        return string + fill * (length - len(unstyled))

    return string
项目:ldap3-cli    作者:cannatag    | 项目源码 | 文件源码
def build_table(name, heading, rows, styles=None, sort=None, max_width=MAX_COL_WIDTH, level=0):
    if rows:
        if max_width == 0:
            max_width = 99999
        lengths = dict()
        max_cols = max(len(heading), len(rows[0]))
        for col in range(max_cols):
            lengths[col] = 0
            for row in [heading] + rows:
                if row:
                    if isinstance(row[col], SEQUENCE_TYPES):
                        for el in row[col]:
                            lengths[col] = max(len(click.unstyle(str(el))[:max_width]), lengths[col])
                    else:
                        lengths[col] = max(len(click.unstyle(str(row[col]))[:max_width]), lengths[col])
        if heading:
            table = [H_SEPARATOR.join([ljust_style(str(element)[:max_width], col, styles, lengths) for col, element in enumerate(heading)]),
                     H_SEPARATOR.join([''.ljust(min(lengths[col], max_width), '=') for col, element in enumerate(heading)])]
        else:
            table = []
        if sort and not isinstance(sort, SEQUENCE_TYPES):
            sort = [sort]
        subrows = []
        sorted_rows = sorted(rows, key=lambda x: [x[i].lower() if hasattr(x[i], 'lower') else x[i] for i in sort]) if sort is not None else rows
        for row in sorted_rows:
            max_depth = max([len(element) if isinstance(element, SEQUENCE_TYPES) else 1 for element in row])
            for depth in range(max_depth):
                subrow = []
                for col in range(max_cols):
                    if isinstance(row[col], SEQUENCE_TYPES):
                        subrow.append(ljust_style(str(row[col][depth])[:max_width], col, styles, lengths) if row[col] and len(row[col]) > depth else ljust_style('', col, styles, lengths))
                    elif depth == 0:
                        subrow.append(ljust_style(str(row[col])[:max_width], col, styles, lengths))
                    else:
                        subrow.append(ljust_style('', col, styles, lengths))
                table.append(H_SEPARATOR.join(subrow))
    else:
        table = ['']
    if name:
        echo_title(name, level=level)
    echo_detail_multiline('', table, level=level + (1 if name else 0))