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


Python click.style方法代碼示例

本文整理匯總了Python中click.style方法的典型用法代碼示例。如果您正苦於以下問題:Python click.style方法的具體用法?Python click.style怎麽用?Python click.style使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在click的用法示例。


在下文中一共展示了click.style方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_django_color

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def test_django_color(capsys):
    call_command("colorcmd")
    out, err = capsys.readouterr()
    # Not passing a --color/--no-color flag defaults to autodetection. As the
    # command is run through the test suite, the autodetection defaults to not
    # colorizing the output.
    assert out == "stdout"
    assert err == "stderr"

    call_command("colorcmd", "--color")
    out, err = capsys.readouterr()
    assert out == click.style("stdout", fg="blue")
    assert err == click.style("stderr", bg="red")

    call_command("colorcmd", "--no-color")
    out, err = capsys.readouterr()
    assert out == "stdout"
    assert err == "stderr" 
開發者ID:GaretJax,項目名稱:django-click,代碼行數:20,代碼來源:test_adapter.py

示例2: parse_page

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def parse_page(page):
    """Parse the command man page."""
    colors = get_config()['colors']
    with io.open(page, encoding='utf-8') as f:
        lines = f.readlines()
    output_lines = []
    for line in lines[1:]:
        if is_headline(line):
            continue
        elif is_description(line):
            output_lines.append(click.style(line.replace('>', ' '),
                                            fg=colors['description']))
        elif is_old_usage(line):
            output_lines.append(click.style(line, fg=colors['usage']))
        elif is_code_example(line):
            line = '  ' + line if line.startswith('`') else line[2:]
            output_lines.append(click.style(line.replace('`', ''),
                                            fg=colors['command']))
        elif is_line_break(line):
            output_lines.append(click.style(line))
        else:
            output_lines.append(click.style('- ' + line, fg=colors['usage']))
    return output_lines 
開發者ID:lord63,項目名稱:tldr.py,代碼行數:25,代碼來源:parser.py

示例3: display_statistic

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def display_statistic(context: ExecutionContext, event: events.Finished) -> None:
    """Format and print statistic collected by :obj:`models.TestResult`."""
    display_section_name("SUMMARY")
    click.echo()
    total = event.total
    if event.is_empty or not total:
        click.secho("No checks were performed.", bold=True)

    if total:
        display_checks_statistics(total)

    if context.cassette_file_name or context.junit_xml_file:
        click.echo()

    if context.cassette_file_name:
        category = click.style("Network log", bold=True)
        click.secho(f"{category}: {context.cassette_file_name}")

    if context.junit_xml_file:
        category = click.style("JUnit XML file", bold=True)
        click.secho(f"{category}: {context.junit_xml_file}") 
開發者ID:kiwicom,項目名稱:schemathesis,代碼行數:23,代碼來源:default.py

示例4: test_handle_initialized

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def test_handle_initialized(capsys, execution_context, results_set, swagger_20):
    # Given Initialized event
    event = runner.events.Initialized.from_schema(schema=swagger_20)
    # When this even is handled
    default.handle_initialized(execution_context, event)
    out = capsys.readouterr().out
    lines = out.split("\n")
    # Then initial title is displayed
    assert " Schemathesis test session starts " in lines[0]
    # And platform information is there
    assert lines[1].startswith("platform")
    # And current directory
    assert f"rootdir: {os.getcwd()}" in lines
    # And number of collected endpoints
    assert strip_style_win32(click.style("collected endpoints: 1", bold=True)) in lines
    # And the output has an empty line in the end
    assert out.endswith("\n\n") 
開發者ID:kiwicom,項目名稱:schemathesis,代碼行數:19,代碼來源:test_default.py

示例5: test_display_statistic

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def test_display_statistic(capsys, swagger_20, execution_context, endpoint):
    # Given multiple successful & failed checks in a single test
    success = models.Check("not_a_server_error", models.Status.success)
    failure = models.Check("not_a_server_error", models.Status.failure)
    single_test_statistic = models.TestResult(
        endpoint, [success, success, success, failure, failure, models.Check("different_check", models.Status.success)]
    )
    results = models.TestResultSet([single_test_statistic])
    event = Finished.from_results(results, running_time=1.0)
    # When test results are displayed
    default.display_statistic(execution_context, event)

    lines = [line for line in capsys.readouterr().out.split("\n") if line]
    failed = strip_style_win32(click.style("FAILED", bold=True, fg="red"))
    passed = strip_style_win32(click.style("PASSED", bold=True, fg="green"))
    # Then all check results should be properly displayed with relevant colors
    assert lines[2:4] == [
        f"    not_a_server_error                    3 / 5 passed          {failed} ",
        f"    different_check                       1 / 1 passed          {passed} ",
    ] 
開發者ID:kiwicom,項目名稱:schemathesis,代碼行數:22,代碼來源:test_default.py

示例6: list_fpgas

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def list_fpgas(self):
        """Return a list with all the supported FPGAs"""

        # Print table
        click.echo('\nSupported FPGAs:\n')

        FPGALIST_TPL = ('{fpga:40} {arch:<8} {type:<12} {size:<5} {pack:<10}')
        terminal_width, _ = click.get_terminal_size()

        click.echo('-' * terminal_width)
        click.echo(FPGALIST_TPL.format(
            fpga=click.style('FPGA', fg='cyan'), type='Type', arch='Arch',
            size='Size', pack='Pack'))
        click.echo('-' * terminal_width)

        for fpga in self.fpgas:
            click.echo(FPGALIST_TPL.format(
                fpga=click.style(fpga, fg='cyan'),
                arch=self.fpgas.get(fpga).get('arch'),
                type=self.fpgas.get(fpga).get('type'),
                size=self.fpgas.get(fpga).get('size'),
                pack=self.fpgas.get(fpga).get('pack'))) 
開發者ID:FPGAwars,項目名稱:apio,代碼行數:24,代碼來源:resources.py

示例7: install

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def install(self):
        click.echo('Installing %s package:' % click.style(
            self.package, fg='cyan'))
        if not isdir(self.packages_dir):
            makedirs(self.packages_dir)
        assert isdir(self.packages_dir)
        dlpath = None
        try:
            # Try full platform
            platform_download_url = self.download_urls[0].get('url')
            dlpath = self._download(platform_download_url)
        except IOError as e:
            click.secho('Warning: permission denied in packages directory',
                        fg='yellow')
            click.secho(str(e), fg='red')
        except Exception:
            # Try os name
            dlpath = self._install_os_package(platform_download_url)

        # Install downloaded package
        self._install_package(dlpath)

        # Rename unpacked dir to package dir
        self._rename_unpacked_dir() 
開發者ID:FPGAwars,項目名稱:apio,代碼行數:26,代碼來源:installer.py

示例8: connect

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def connect(self, state, for_fact=None, show_errors=True):
        if not self.connection:
            try:
                self.connection = self.executor.connect(state, self)
            except ConnectError as e:
                if show_errors:
                    log_message = '{0}{1}'.format(
                        self.print_prefix,
                        click.style(e.args[0], 'red'),
                    )
                    logger.error(log_message)
            else:
                log_message = '{0}{1}'.format(
                    self.print_prefix,
                    click.style('Connected', 'green'),
                )
                if for_fact:
                    log_message = '{0}{1}'.format(
                        log_message,
                        ' (for {0} fact)'.format(for_fact),
                    )

                logger.info(log_message)

        return self.connection 
開發者ID:Fizzadar,項目名稱:pyinfra,代碼行數:27,代碼來源:host.py

示例9: disconnect

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def disconnect(state, host):
    container_id = host.host_data['docker_container_id'][:12]

    with progress_spinner({'docker commit'}):
        image_id = local.shell(
            'docker commit {0}'.format(container_id),
            splitlines=True,
        )[-1][7:19]  # last line is the image ID, get sha256:[XXXXXXXXXX]...

    with progress_spinner({'docker rm'}):
        local.shell(
            'docker rm -f {0}'.format(container_id),
        )

    logger.info('{0}docker build complete, image ID: {1}'.format(
        host.print_prefix, click.style(image_id, bold=True),
    )) 
開發者ID:Fizzadar,項目名稱:pyinfra,代碼行數:19,代碼來源:docker.py

示例10: load_deploy_file

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def load_deploy_file(state, filename):
    # Copy the inventory hosts (some might be removed during deploy)
    hosts = list(state.inventory)

    for host in hosts:
        # Don't load for anything within our (top level, --limit) limit
        if (
            isinstance(state.limit_hosts, list)
            and host not in state.limit_hosts
        ):
            continue

        pseudo_host.set(host)

        exec_file(filename)

        logger.info('{0}{1} {2}'.format(
            host.print_prefix,
            click.style('Ready:', 'green'),
            click.style(filename, bold=True),
        ))

    # Remove any pseudo host
    pseudo_host.reset() 
開發者ID:Fizzadar,項目名稱:pyinfra,代碼行數:26,代碼來源:util.py

示例11: process

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def process(self):
        terminal_width, _ = click.get_terminal_size()
        start_time = time()

        click.echo("[%s] Processing %s (%s)" % (
            datetime.now().strftime("%c"),
            click.style(self.name, fg="cyan", bold=True),
            ", ".join(["%s: %s" % (k, v) for k, v in self.options.iteritems()])
        ))
        click.secho("-" * terminal_width, bold=True)

        result = self._run()

        is_error = result['returncode'] != 0
        summary_text = " Took %.2f seconds " % (time() - start_time)
        half_line = "=" * ((terminal_width - len(summary_text) - 10) / 2)
        click.echo("%s [%s]%s%s" % (
            half_line,
            (click.style(" ERROR ", fg="red", bold=True)
             if is_error else click.style("SUCCESS", fg="green", bold=True)),
            summary_text,
            half_line
        ), err=is_error)

        return not is_error, result # [JORGE_GARCIA] added result to the return for further use 
開發者ID:bq,項目名稱:web2board,代碼行數:27,代碼來源:run.py

示例12: platforms_list

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def platforms_list(json_output):

    installed_platforms = PlatformFactory.get_platforms(
        installed=True).keys()
    installed_platforms.sort()

    data = []
    for platform in installed_platforms:
        p = PlatformFactory.newPlatform(platform)
        data.append({
            "name": platform,
            "packages": p.get_installed_packages()
        })

    if json_output:
        click.echo(json.dumps(data))
    else:
        for item in data:
            click.echo("{name:<20} with packages: {pkgs}".format(
                name=click.style(item['name'], fg="cyan"),
                pkgs=", ".join(item['packages'])
            )) 
開發者ID:bq,項目名稱:web2board,代碼行數:24,代碼來源:platforms.py

示例13: update

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def update(self, name):
        click.echo("Updating %s package:" % click.style(name, fg="yellow"))

        installed = self.get_installed()
        current_version = installed[name]['version']
        latest_version = self.get_info(name)['version']

        click.echo("Versions: Current=%d, Latest=%d \t " %
                   (current_version, latest_version), nl=False)

        if current_version == latest_version:
            click.echo("[%s]" % (click.style("Up-to-date", fg="green")))
            return True
        else:
            click.echo("[%s]" % (click.style("Out-of-date", fg="red")))

        self.uninstall(name)
        self.install(name)

        telemetry.on_event(
            category="PackageManager", action="Update", label=name) 
開發者ID:bq,項目名稱:web2board,代碼行數:23,代碼來源:pkgmanager.py

示例14: error

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def error(s: str) -> None:
    click.echo(style("ERROR: ", fg="red") + s) 
開發者ID:trezor,項目名稱:python-shamir-mnemonic,代碼行數:4,代碼來源:cli.py

示例15: invoke

# 需要導入模塊: import click [as 別名]
# 或者: from click import style [as 別名]
def invoke(self, ctx):
        try:
            return super(DjangoCommandMixin, self).invoke(ctx)
        except CommandError as e:
            # Honor the --traceback flag
            if ctx.traceback:  # NOCOV
                raise
            styled_message = click.style(
                "{}: {}".format(e.__class__.__name__, e), fg="red", bold=True
            )
            click.echo(styled_message, err=True)
            ctx.exit(1) 
開發者ID:GaretJax,項目名稱:django-click,代碼行數:14,代碼來源:adapter.py


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