Python click.secho() Examples

The following are 30 code examples for showing how to use click.secho(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module click , or try the search function .

Example 1
Project: goodtables-py   Author: frictionlessdata   File: cli.py    License: 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 2
Project: ng   Author: cls1991   File: ng.py    License: 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 3
Project: EulerPy   Author: iKevinY   File: problem.py    License: 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 4
Project: EulerPy   Author: iKevinY   File: problem.py    License: 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 5
Project: datasette   Author: simonw   File: common.py    License: 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 6
Project: ivona-speak   Author: Pythonity   File: command_line.py    License: 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 7
Project: ivona-speak   Author: Pythonity   File: command_line.py    License: 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 8
Project: recruit   Author: Frank-qlu   File: cli.py    License: 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 9
Project: schemathesis   Author: kiwicom   File: __init__.py    License: 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 10
Project: schemathesis   Author: kiwicom   File: callbacks.py    License: 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 11
Project: schemathesis   Author: kiwicom   File: default.py    License: 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 12
Project: apio   Author: FPGAwars   File: system.py    License: 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 13
Project: apio   Author: FPGAwars   File: upgrade.py    License: 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
Project: apio   Author: FPGAwars   File: drivers.py    License: 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 15
Project: apio   Author: FPGAwars   File: examples.py    License: 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 16
Project: apio   Author: FPGAwars   File: __main__.py    License: 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 17
Project: apio   Author: FPGAwars   File: util.py    License: 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 18
Project: apio   Author: FPGAwars   File: util.py    License: 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 19
Project: apio   Author: FPGAwars   File: installer.py    License: 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 20
Project: apio   Author: FPGAwars   File: installer.py    License: 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 21
Project: apio   Author: FPGAwars   File: installer.py    License: 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 22
Project: goodtables-py   Author: frictionlessdata   File: cli.py    License: MIT License 5 votes vote down vote up
def _print_report(report, output=None, json=False):
    def secho(*args, **kwargs):
        click.secho(file=output, *args, **kwargs)

    if json:
        return secho(json_module.dumps(report, indent=4))

    color = 'green' if report['valid'] else 'red'
    tables = report.pop('tables')
    warnings = report.pop('warnings')
    secho('DATASET', bold=True)
    secho('='*7, bold=True)
    secho(pformat(report), fg=color, bold=True)
    if warnings:
        secho('-'*9, bold=True)
    for warning in warnings:
        secho('Warning: %s' % warning, fg='yellow')
    for table_number, table in enumerate(tables, start=1):
        secho('\nTABLE [%s]' % table_number, bold=True)
        secho('='*9, bold=True)
        color = 'green' if table['valid'] else 'red'
        errors = table.pop('errors')
        secho(pformat(table), fg=color, bold=True)
        if errors:
            secho('-'*9, bold=True)
        for error in errors:
            template = '[{row-number},{column-number}] [{code}] {message}'
            substitutions = {
                'row-number': error.get('row-number', '-'),
                'column-number': error.get('column-number', '-'),
                'code': error.get('code', '-'),
                'message': error.get('message', '-'),
            }
            message = template.format(**substitutions)
            secho(message)


# Main 
Example 23
Project: wio-cli   Author: Seeed-Studio   File: cmd_delete.py    License: MIT License 5 votes vote down vote up
def cli(wio, sn):
    '''
    Delete a device.

    \b
    DOES:
        Delete a device.
        sn: device_sn
        wio delete <device_sn>

    \b
    EXAMPLE:
        wio delete 2885b2cab8abc5fb8e229e4a77bf5e4d
    '''
    user_token = wio.config.get("token", None)
    api_prefix = wio.config.get("mserver", None)
    if not api_prefix or not user_token:
        click.echo(click.style('>> ', fg='red') + "Please login, use " +
            click.style("wio login", fg='green'))
        return

    params = {"access_token":user_token, "node_sn":sn}
    try:
        r = requests.post("%s%s" %(api_prefix, nodes_delete_endpoint), params=params, timeout=10, verify=verify)
        r.raise_for_status()
        json_response = r.json()
    except requests.exceptions.HTTPError as e:
        if r.status_code == 400:
            error = r.json().get("error", None)
            click.secho(">> %s" %error, fg='red')
        else:
            click.secho(">> %s" %e, fg='red')
        return
    except Exception as e:
        click.secho(">> %s" %e, fg='red')
        return

    click.secho('>> Delete device commplete!', fg='white') 
Example 24
Project: wio-cli   Author: Seeed-Studio   File: cmd_setup.py    License: MIT License 5 votes vote down vote up
def get_new(mserver_url, token, board):
    '''get node sn and key'''
    thread = termui.waiting_echo("Getting message from Server...")
    thread.daemon = True
    thread.start()
    try:
        params = {"name":"node000", "board":board, "access_token":token}
        r = requests.post("%s%s" %(mserver_url, nodes_create_endpoint), params=params, timeout=10, verify=verify)
        r.raise_for_status()
        json_response = r.json()
    except requests.exceptions.HTTPError as e:
        thread.stop('')
        thread.join()
        if r.status_code == 400:
            error = r.json().get("error", None)
            click.secho(">> %s" %error, fg='red')
        else:
            click.secho(">> %s" %e, fg='red')
        return None
    except Exception as e:
        thread.stop('')
        thread.join()
        click.secho(">> %s" %e, fg='red')
        return None

    thread.stop('')
    thread.join()

    return json_response 
Example 25
Project: wio-cli   Author: Seeed-Studio   File: cmd_state.py    License: MIT License 5 votes vote down vote up
def cli(wio):
    '''
    Login state.

    \b
    DOES:
        Display login email, token, server url.

    \b
    USE:
        wio state
    '''
    user_token = wio.config.get("token", None)
    mserver_url = wio.config.get("mserver", None)
    if not mserver_url or not user_token:
        click.echo(click.style('>> ', fg='red') + "Please login, use " +
            click.style("wio login", fg='green'))
        return

    email = wio.config.get("email",None)
    server = wio.config.get("server",None)
    token = wio.config.get("token",None)
    click.secho('> ', fg='green', nl=False)
    click.echo("server: " + click.style(server, fg='green', bold=True) + ', ' +
        click.style(mserver_url, fg='green', bold=True))
    click.secho('> ', fg='green', nl=False)
    click.echo("email:  " + click.style(email, fg='green', bold=True))
    click.secho('> ', fg='green', nl=False)
    click.echo("token:  " + click.style(token, fg='green', bold=True)) 
Example 26
Project: evolution-strategies-starter   Author: openai   File: launch.py    License: MIT License 5 votes vote down vote up
def highlight(x):
    if not isinstance(x, str):
        x = json.dumps(x, sort_keys=True, indent=2)
    click.secho(x, fg='green') 
Example 27
Project: ng   Author: cls1991   File: ng.py    License: Apache License 2.0 5 votes vote down vote up
def ip():
    """Show ip address."""
    ok, err = _hack_ip()
    if not ok:
        click.secho(click.style(err, fg='red'))
        sys.exit(1)
    click.secho(click.style(err, fg='green')) 
Example 28
Project: respy   Author: OpenSourceEconomics   File: regression.py    License: MIT License 5 votes vote down vote up
def run_regression_tests(n_tests, strict, notification):
    """Run regression tests.

    Parameters
    ----------
    n_tests : int
        Number of tests to run. If None, all are run.
    strict : bool, default False
        Early failure on error.
    notification : bool, default True
        Send notification with test report.

    """
    tests = load_regression_tests()
    tests = tests[: n_tests + 1]

    results = [_check_single(test, strict) for test in tests]
    idx_failures = [i for i, x in enumerate(results) if not x]

    if idx_failures:
        click.secho(f"Failures: {idx_failures}", fg="red")
    else:
        click.secho(f"Tests succeeded.", fg="green")

    subject, message = _prepare_message(idx_failures)

    if notification:
        from development.testing.notifications import send_notification

        send_notification(subject, message) 
Example 29
Project: respy   Author: OpenSourceEconomics   File: testing_pull_request.py    License: MIT License 5 votes vote down vote up
def run_pull_request_tests():
    is_short_run = socket.gethostname() in ["abacus", "socrates"]

    click.secho("Starting pytest", fg="green")
    rp.test()
    click.secho("Stopping pytest", fg="green")

    n_tests = 50 if is_short_run else 1000

    runner = CliRunner()

    click.secho("Starting regression test.", fg="green")
    runner.invoke(run, [str(n_tests), "--strict"])
    click.secho("Stopping regression test.", fg="green") 
Example 30
Project: catt   Author: skorokithakis   File: util.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def echo_warning(msg):
    click.secho("Warning: ", fg="red", nl=False, err=True)
    click.echo("{}.".format(msg), err=True)