Python click.secho() Examples

The following are 30 code examples of click.secho(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: examples.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def cli(ctx, list, dir, files, project_dir, sayno):
    """Manage verilog examples.\n
       Install with `apio install examples`"""

    exit_code = 0

    if list:
        exit_code = Examples().list_examples()
    elif dir:
        exit_code = Examples().copy_example_dir(dir, project_dir, sayno)
    elif files:
        exit_code = Examples().copy_example_files(files, project_dir, sayno)
    else:
        click.secho(ctx.get_help())
        click.secho(Examples().examples_of_use_cad())

    ctx.exit(exit_code) 
Example #2
Source File: installer.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def _install_os_package(self, platform_download_url):
        os_download_url = self.download_urls[1].get('url')
        if platform_download_url != os_download_url:
            click.secho(
                'Warning: full platform does not match: {}\
                '.format(self.download_urls[0].get('platform')),
                fg='yellow')
            click.secho(
                '         Trying OS name: {}\
                '.format(self.download_urls[1].get('platform')),
                fg='yellow')
            try:
                return self._download(os_download_url)
            except Exception as e:
                click.secho(
                    'Error: {}'.format(str(e)),
                    fg='red')
        else:
            click.secho(
                'Error: package not availabe for this platform',
                fg='red') 
Example #3
Source File: util.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def get_pypi_latest_version():
    r = None
    version = None
    try:
        r = requests.get('https://pypi.python.org/pypi/apio/json')
        version = r.json().get('info').get('version')
        r.raise_for_status()
    except requests.exceptions.ConnectionError as e:
        error_message = str(e)
        if 'NewConnectionError' in error_message:
            click.secho('Error: could not connect to Pypi.\n'
                        'Check your internet connection and try again',
                        fg='red')
        else:
            click.secho(error_message, fg='red')
    except Exception as e:
        click.secho('Error: ' + str(e), fg='red')
    finally:
        if r:
            r.close()
    return version 
Example #4
Source File: util.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def check_dir(_dir):
    if _dir is None:
        _dir = os.getcwd()

    if isfile(_dir):
        click.secho(
            'Error: project directory is already a file: {0}'.format(_dir),
            fg='red')
        exit(1)

    if not exists(_dir):
        try:
            os.makedirs(_dir)
        except OSError:
            pass
    return _dir 
Example #5
Source File: installer.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def _download(self, url):
        # Note: here we check only for the version of locally installed
        # packages. For this reason we don't say what's the installation
        # path.
        if not self.profile.installed_version(self.package, self.version) \
           or self.force_install:
            fd = FileDownloader(url, self.packages_dir)
            filepath = fd.get_filepath()
            click.secho('Download ' + basename(filepath))
            try:
                fd.start()
            except KeyboardInterrupt:
                if isfile(filepath):
                    remove(filepath)
                click.secho('Abort download!', fg='red')
                exit(1)
            return filepath
        else:
            click.secho('Already installed. Version {0}'.format(
                self.profile.get_package_version(self.package)), fg='yellow')
            return None 
Example #6
Source File: installer.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
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() 
Example #7
Source File: ng.py    From ng with Apache License 2.0 6 votes vote down vote up
def wp(ssid):
    """Show wifi password."""
    if not ssid:
        ok, err = _detect_wifi_ssid()
        if not ok:
            click.secho(click.style(err, fg='red'))
            sys.exit(1)
        ssid = err
    ok, err = _hack_wifi_password(ssid)
    if not ok:
        click.secho(click.style(err, fg='red'))
        sys.exit(1)
    click.secho(click.style('{ssid}:{password}'.format(ssid=ssid, password=err), fg='green'))


# Install click commands. 
Example #8
Source File: problem.py    From EulerPy with MIT License 6 votes vote down vote up
def solution(self):
        """Returns the answer to a given problem"""
        num = self.num

        solution_file = os.path.join(EULER_DATA, 'solutions.txt')
        solution_line = linecache.getline(solution_file, num)

        try:
            answer = solution_line.split('. ')[1].strip()
        except IndexError:
            answer = None

        if answer:
            return answer
        else:
            msg = 'Answer for problem %i not found in solutions.txt.' % num
            click.secho(msg, fg='red')
            click.echo('If you have an answer, consider submitting a pull '
                       'request to EulerPy on GitHub.')
            sys.exit(1) 
Example #9
Source File: __main__.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def cli(ctx):

    # Update help structure
    if ctx.invoked_subcommand is None:
        help = ctx.get_help()
        help = help.split('\n')

        setup_help = find_commands_help(help, ['drivers', 'init',
                                               'install', 'uninstall'])
        util_help = find_commands_help(help, ['boards', 'config', 'examples',
                                              'raw', 'system', 'upgrade'])

        help = '\n'.join(help)
        help = help.replace('Commands:\n', 'Project commands:\n')
        help += "\n\nSetup commands:\n"
        help += '\n'.join(setup_help)
        help += "\n\nUtility commands:\n"
        help += '\n'.join(util_help)

        click.secho(help) 
Example #10
Source File: problem.py    From EulerPy with MIT License 6 votes vote down vote up
def copy_resources(self):
        """Copies the relevant resources to a resources subdirectory"""
        if not os.path.isdir('resources'):
            os.mkdir('resources')

        resource_dir = os.path.join(os.getcwd(), 'resources', '')
        copied_resources = []

        for resource in self.resources:
            src = os.path.join(EULER_DATA, 'resources', resource)
            if os.path.isfile(src):
                shutil.copy(src, resource_dir)
                copied_resources.append(resource)

        if copied_resources:
            copied = ', '.join(copied_resources)
            path = os.path.relpath(resource_dir, os.pardir)
            msg = "Copied {} to {}.".format(copied, path)

            click.secho(msg, fg='green') 
Example #11
Source File: drivers.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable):
    """Manage FPGA boards drivers."""

    exit_code = 0

    if ftdi_enable:   # pragma: no cover
        exit_code = Drivers().ftdi_enable()
    elif ftdi_disable:   # pragma: no cover
        exit_code = Drivers().ftdi_disable()
    elif serial_enable:   # pragma: no cover
        exit_code = Drivers().serial_enable()
    elif serial_disable:   # pragma: no cover
        exit_code = Drivers().serial_disable()
    else:
        click.secho(ctx.get_help())

    ctx.exit(exit_code) 
Example #12
Source File: common.py    From datasette with Apache License 2.0 6 votes vote down vote up
def fail_if_publish_binary_not_installed(binary, publish_target, install_link):
    """Exit (with error message) if ``binary` isn't installed"""
    if not shutil.which(binary):
        click.secho(
            "Publishing to {publish_target} requires {binary} to be installed and configured".format(
                publish_target=publish_target, binary=binary
            ),
            bg="red",
            fg="white",
            bold=True,
            err=True,
        )
        click.echo(
            "Follow the instructions at {install_link}".format(
                install_link=install_link
            ),
            err=True,
        )
        sys.exit(1) 
Example #13
Source File: upgrade.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def cli(ctx):
    """Check the latest Apio version."""

    current_version = get_distribution('apio').version
    latest_version = get_pypi_latest_version()

    if latest_version is None:
        ctx.exit(1)

    if latest_version == current_version:
        click.secho('You\'re up-to-date!\nApio {} is currently the '
                    'newest version available.'.format(latest_version),
                    fg='green')
    else:
        click.secho('You\'re not updated\nPlease execute '
                    '`pip install -U apio` to upgrade.',
                    fg="yellow") 
Example #14
Source File: command_line.py    From ivona-speak with MIT License 6 votes vote down vote up
def synthesize(access_key, secret_key, output_file, voice_name, voice_language,
               codec, text):
    """Synthesize passed text and save it as an audio file"""
    try:
        ivona_api = IvonaAPI(
            access_key, secret_key,
            voice_name=voice_name, language=voice_language, codec=codec,
        )
    except (ValueError, IvonaAPIException) as e:
        raise click.ClickException("Something went wrong: {}".format(repr(e)))

    with click.open_file(output_file, 'wb') as file:
        ivona_api.text_to_speech(text, file)

    click.secho(
        "File successfully saved as '{}'".format(output_file),
        fg='green',
    ) 
Example #15
Source File: command_line.py    From ivona-speak with MIT License 6 votes vote down vote up
def list_voices(access_key, secret_key, voice_language, voice_gender):
    """List available Ivona voices"""
    try:
        ivona_api = IvonaAPI(access_key, secret_key)
    except (ValueError, IvonaAPIException) as e:
        raise click.ClickException("Something went wrong: {}".format(repr(e)))

    click.echo("Listing available voices...")

    voices_list = ivona_api.get_available_voices(
        language=voice_language,
        gender=voice_gender,
    )

    # Group voices by language
    voices_dict = dict()
    data = sorted(voices_list, key=lambda x: x['Language'])
    for k, g in groupby(data, key=lambda x: x['Language']):
        voices_dict[k] = list(g)

    for ln, voices in voices_dict.items():
        voice_names = [v['Name'] for v in voices]
        click.echo("{}: {}".format(ln, ', '.join(voice_names)))

    click.secho("All done", fg='green') 
Example #16
Source File: system.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def cli(ctx, lsftdi, lsusb, lsserial, info):
    """System tools.\n
       Install with `apio install system`"""

    exit_code = 0

    if lsftdi:
        exit_code = System().lsftdi()
    elif lsusb:
        exit_code = System().lsusb()
    elif lsserial:
        exit_code = System().lsserial()
    elif info:
        click.secho('Platform: ', nl=False)
        click.secho(get_systype(), fg='yellow')
    else:
        click.secho(ctx.get_help())

    ctx.exit(exit_code) 
Example #17
Source File: cli.py    From recruit with Apache License 2.0 6 votes vote down vote up
def show_server_banner(env, debug, app_import_path, eager_loading):
    """Show extra startup messages the first time the server is run,
    ignoring the reloader.
    """
    if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        return

    if app_import_path is not None:
        message = ' * Serving Flask app "{0}"'.format(app_import_path)

        if not eager_loading:
            message += ' (lazy loading)'

        click.echo(message)

    click.echo(' * Environment: {0}'.format(env))

    if env == 'production':
        click.secho(
            '   WARNING: Do not use the development server in a production'
            ' environment.', fg='red')
        click.secho('   Use a production WSGI server instead.', dim=True)

    if debug is not None:
        click.echo(' * Debug mode: {0}'.format('on' if debug else 'off')) 
Example #18
Source File: __init__.py    From schemathesis with MIT License 6 votes vote down vote up
def replay(
    cassette_path: str,
    id_: Optional[str],
    status: Optional[str] = None,
    uri: Optional[str] = None,
    method: Optional[str] = None,
) -> None:
    """Replay a cassette.

    Cassettes in VCR-compatible format can be replayed.
    For example, ones that are recorded with ``store-network-log`` option of `schemathesis run` command.
    """
    click.secho(f"{bold('Replaying cassette')}: {cassette_path}")
    with open(cassette_path) as fd:
        cassette = yaml.load(fd, Loader=SafeLoader)
    click.secho(f"{bold('Total interactions')}: {len(cassette['http_interactions'])}\n")
    for replayed in cassettes.replay(cassette, id_=id_, status=status, uri=uri, method=method):
        click.secho(f"  {bold('ID')}              : {replayed.interaction['id']}")
        click.secho(f"  {bold('URI')}             : {replayed.interaction['request']['uri']}")
        click.secho(f"  {bold('Old status code')} : {replayed.interaction['response']['status']['code']}")
        click.secho(f"  {bold('New status code')} : {replayed.response.status_code}\n") 
Example #19
Source File: callbacks.py    From schemathesis with MIT License 6 votes vote down vote up
def validate_app(ctx: click.core.Context, param: click.core.Parameter, raw_value: Optional[str]) -> Optional[str]:
    if raw_value is None:
        return raw_value
    try:
        utils.import_app(raw_value)
        # String is returned instead of an app because it might be passed to a subprocess
        # Since most of app instances are not-transferable to another process, they are passed as strings and
        # imported in a subprocess
        return raw_value
    except Exception as exc:
        show_errors_tracebacks = ctx.params["show_errors_tracebacks"]
        message = utils.format_exception(exc, show_errors_tracebacks)
        click.secho(f"{message}\nCan not import application from the given module", fg="red")
        if not show_errors_tracebacks:
            click.secho(
                "Add this option to your command line parameters to see full tracebacks: --show-errors-tracebacks",
                fg="red",
            )
        raise click.exceptions.Exit(1) 
Example #20
Source File: cli.py    From goodtables-py with MIT License 6 votes vote down vote up
def init(paths, output, **kwargs):
    """Init data package from list of files.

    It will also infer tabular data's schemas from their contents.
    """
    dp = init_datapackage(paths)

    click.secho(
        json_module.dumps(dp.descriptor, indent=4),
        file=output
    )

    exit(int(not dp.valid))  # Just to be defensive, as it should always be valid.


# Internal 
Example #21
Source File: default.py    From schemathesis with MIT License 6 votes vote down vote up
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}") 
Example #22
Source File: installer.py    From apio with GNU General Public License v2.0 5 votes vote down vote up
def _find_required_version(self, releases, tag_name, req_v, spec_v):
        for release in releases:
            if 'tag_name' in release:
                tag = tag_name.replace('%V', req_v)
                if tag == release.get('tag_name'):
                    prerelease = release.get('prerelease', False)
                    if prerelease and not self.force_install:
                        click.secho(
                            'Warning: ' + req_v + ' is' +
                            ' a pre-release. Use --force to install',
                            fg='yellow')
                        exit(1)
                    return req_v 
Example #23
Source File: scons.py    From apio with GNU General Public License v2.0 5 votes vote down vote up
def check_pip_packages(self, board_data):
        prog_info = board_data.get('programmer')
        content = self.resources.programmers.get(prog_info.get('type'))
        all_pip_packages = self.resources.distribution.get('pip_packages')

        pip_packages = content.get('pip_packages') or []
        for pip_pkg in pip_packages:
            try:
                # Check pip_package version
                spec = semantic_version.Spec(all_pip_packages.get(pip_pkg, ''))
                pkg_version = pkg_resources.get_distribution(pip_pkg).version
                version = semantic_version.Version(pkg_version)
                if not spec.match(version):
                    click.secho(
                        'Error: \'{}\' '.format(pip_pkg) +
                        'version ({}) '.format(version) +
                        'does not match {}'.format(spec),
                        fg='red')
                    click.secho('Please run:\n'
                                '   pip install -U apio[{}]'.format(pip_pkg),
                                fg='yellow')
                    raise Exception
            except pkg_resources.DistributionNotFound:
                click.secho(
                    'Error: \'{}\' is not installed'.format(pip_pkg),
                    fg='red')
                click.secho('Please run:\n'
                            '   pip install -U apio[{}]'.format(pip_pkg),
                            fg='yellow')
                raise Exception
            try:
                # Check pip_package itself
                __import__(pip_pkg)
            except Exception as e:
                # Exit if a package is not working
                python_version = util.get_python_version()
                message = '\'{}\' not compatible with '.format(pip_pkg)
                message += 'Python {}'.format(python_version)
                message += '\n       {}'.format(e)
                raise Exception(message) 
Example #24
Source File: default.py    From schemathesis with MIT License 5 votes vote down vote up
def display_checks_statistics(total: Dict[str, Dict[Union[str, Status], int]]) -> None:
    padding = 20
    col1_len = max(map(len, total.keys())) + padding
    col2_len = len(str(max(total.values(), key=lambda v: v["total"])["total"])) * 2 + padding
    col3_len = padding
    click.secho("Performed checks:", bold=True)
    template = f"    {{:{col1_len}}}{{:{col2_len}}}{{:{col3_len}}}"
    for check_name, results in total.items():
        display_check_result(check_name, results, template) 
Example #25
Source File: util.py    From apio with GNU General Public License v2.0 5 votes vote down vote up
def show_package_install_instructions(name):
    if config_data and _check_apt_get():  # /etc/apio.json file exists
        click.secho('Please run:\n'
                    '   apt-get install apio-{}'.format(name), fg='yellow')
    else:
        click.secho('Please run:\n'
                    '   apio install {}'.format(name), fg='yellow') 
Example #26
Source File: default.py    From schemathesis with MIT License 5 votes vote down vote up
def handle_initialized(context: ExecutionContext, event: events.Initialized) -> None:
    """Display information about the test session."""
    context.endpoints_count = event.endpoints_count
    display_section_name("Schemathesis test session starts")
    versions = (
        f"platform {platform.system()} -- "
        f"Python {platform.python_version()}, "
        f"schemathesis-{__version__}, "
        f"hypothesis-{metadata.version('hypothesis')}, "
        f"hypothesis_jsonschema-{metadata.version('hypothesis_jsonschema')}, "
        f"jsonschema-{metadata.version('jsonschema')}"
    )
    click.echo(versions)
    click.echo(f"rootdir: {os.getcwd()}")
    click.echo(
        f"hypothesis profile '{settings._current_profile}' "  # type: ignore
        f"-> {settings.get_profile(settings._current_profile).show_changed()}"
    )
    if event.location is not None:
        click.echo(f"Schema location: {event.location}")
    click.echo(f"Base URL: {event.base_url}")
    click.echo(f"Specification version: {event.specification_name}")
    click.echo(f"Workers: {context.workers_num}")
    click.secho(f"collected endpoints: {event.endpoints_count}", bold=True)
    if event.endpoints_count >= 1:
        click.echo() 
Example #27
Source File: profile.py    From apio with GNU General Public License v2.0 5 votes vote down vote up
def add_config(self, key, value):
        if self.config.get(key, None) != value:
            self.config[key] = value
            self.save()
            click.secho('{0} mode updated: {1}'.format(
                self.labels.get(key, ''), value), fg='green')
        else:
            click.secho('{0} mode already {1}'.format(
                self.labels.get(key, ''), value), fg='yellow') 
Example #28
Source File: profile.py    From apio with GNU General Public License v2.0 5 votes vote down vote up
def list(self):
        for key in self.config:
            click.secho('{0} mode: {1}'.format(
                    self.labels.get(key, ''), self.config.get(key, '')),
                fg='yellow') 
Example #29
Source File: system.py    From apio with GNU General Public License v2.0 5 votes vote down vote up
def _on_stderr(self, line):
        click.secho(line, fg='red') 
Example #30
Source File: tool.py    From Bowler with MIT License 5 votes vote down vote up
def prompt_user(question: str, options: str, default: str = "") -> str:
    options = options.lower()
    default = default.lower()
    assert len(default) < 2 and default in options

    if "?" not in options:
        options += "?"

    prompt_options = ",".join(o.upper() if o == default else o for o in options)
    prompt = f"{question} [{prompt_options}]? "
    result = ""

    while True:
        result = input(prompt).strip().lower()
        if result == "?":
            for option in PROMPT_HELP:
                click.secho(f"{option} - {PROMPT_HELP[option]}", fg="red", bold=True)

        elif len(result) == 1 and result in options:
            return result

        elif result:
            click.echo(f'invalid response "{result}"')

        elif default:
            return default