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


Python click.ClickException方法代碼示例

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


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

示例1: run_from_argv

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def run_from_argv(self, argv):
        """
        Called when run from the command line.
        """
        prog_name = "{} {}".format(os.path.basename(argv[0]), argv[1])
        try:
            # We won't get an exception here in standalone_mode=False
            exit_code = self.main(
                args=argv[2:], prog_name=prog_name, standalone_mode=False
            )
            if exit_code:
                sys.exit(exit_code)
        except click.ClickException as e:
            if getattr(e.ctx, "traceback", False):  # NOCOV
                raise
            e.show()
            sys.exit(e.exit_code) 
開發者ID:GaretJax,項目名稱:django-click,代碼行數:19,代碼來源:adapter.py

示例2: certidude_housekeeping_kinit

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def certidude_housekeeping_kinit():
    from certidude import config

    # Update LDAP service ticket if Certidude is joined to domain
    if not os.path.exists("/etc/krb5.keytab"):
        raise click.ClickException("No Kerberos keytab configured")

    _, kdc = config.LDAP_ACCOUNTS_URI.rsplit("/", 1)
    cmd = "KRB5CCNAME=%s.part kinit -k %s$ -S ldap/%s@%s -t /etc/krb5.keytab" % (
        config.LDAP_GSSAPI_CRED_CACHE,
        const.HOSTNAME.upper(), kdc, config.KERBEROS_REALM
    )
    click.echo("Executing: %s" % cmd)
    if os.system(cmd):
        raise click.ClickException("Failed to initialize Kerberos credential cache!")
    os.system("chown certidude:certidude %s.part" % config.LDAP_GSSAPI_CRED_CACHE)
    os.rename("%s.part" % config.LDAP_GSSAPI_CRED_CACHE, config.LDAP_GSSAPI_CRED_CACHE) 
開發者ID:laurivosandi,項目名稱:certidude,代碼行數:19,代碼來源:cli.py

示例3: synthesize

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
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',
    ) 
開發者ID:Pythonity,項目名稱:ivona-speak,代碼行數:20,代碼來源:command_line.py

示例4: list_voices

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
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') 
開發者ID:Pythonity,項目名稱:ivona-speak,代碼行數:27,代碼來源:command_line.py

示例5: arg_date

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def arg_date(var='date', metavar='<date>', date_frmt_key='date_frmt'):
    def _arg_date(f):
        def callback(ctx, param, value):
            try:
                value = dt.strptime(value, ctx.params[date_frmt_key])
            except KeyError:
                raise click.ClickException(
                    'Need to use `date_format_opt` when using `date_arg`')
            except ValueError:
                raise click.BadParameter(
                    'Cannot parse {v} to date with format {f}'.format(
                        v=value, f=ctx.params['date_frmt']))
            else:
                return value
        return click.argument(var, metavar=metavar, callback=callback)(f)
    return _arg_date 
開發者ID:ceholden,項目名稱:yatsm,代碼行數:18,代碼來源:options.py

示例6: do_subprocess

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def do_subprocess(cmd, stdout=True, stderr=True, check=True, timeout=2):
    assert sys.version_info >= (3,5)
    kwargs = dict(
        stdout=subprocess.PIPE if stdout else None,
        stderr=subprocess.PIPE if stderr else None,
        shell=True,
        check=False,
        timeout=timeout,
    )

    try:
        result = subprocess.run(cmd, **kwargs)
    except subprocess.TimeoutExpired:
        msg = "Command '{}' timed out after waiting for {} seconds"
        raise ClickException(msg.format(cmd, timeout))

    if check and result.returncode:
        errno = result.returncode
        error = result.stderr.decode().strip()
        msg = "Command '{}' returned non-zero exit status {}\n{}"
        raise ClickException(msg.format(cmd, errno, error))

    return result 
開發者ID:kblomqvist,項目名稱:yasha,代碼行數:25,代碼來源:filters.py

示例7: cli

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def cli(ctx, password):
    if not hasattr(ctx.obj, 'key'):
        ctx.obj = LokeyContext()
    interactive_terminal = sys.__stdin__.isatty()
    subcommand = ctx.invoked_subcommand
    if interactive_terminal and not subcommand:
        print("\n".join([
            ctx.get_help(),
            "",
            "Examples:",
            "  $ cat your-key | lokey to ssh",
            "  $ lokey fetch keybase twitter:jf",
            ""]))
        return
    elif interactive_terminal and subcommand:
        return
    try:
        ctx.obj.key = eris.load(sys.stdin, password=password)
    except Exception as e:
        raise click.ClickException(str(e))
    if not subcommand:
        print ctx.obj.key 
開發者ID:jpf,項目名稱:lokey,代碼行數:24,代碼來源:__init__.py

示例8: do_tag

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def do_tag(config, force, src, requirement, yes, dry_run=False):
    tag = config.version
    if not yes:
        click.confirm("Tag project with {}?".format(tag), abort=True)
    if force:
        force_cmd = ["-f"]
    else:
        force_cmd = []
    if call(["git", "diff", "--exit-code"]) != 0:
        raise click.ClickException("Please commit first.")
    if call(["git", "diff", "--exit-code", "--cached"]) != 0:
        raise click.ClickException("Please commit first.")
    out = check_output(
        ["git", "ls-files", "--other", "--exclude-standard", "--directory"]
    )
    if out:
        click.echo(out)
        raise click.ClickException("Please commit first.")
    do_tag_requirements(config, src, requirement, yes=True, dry_run=dry_run)
    click.echo("placing tag {tag} on origin".format(**locals()))
    if not dry_run:
        check_call(["git", "tag"] + force_cmd + [tag])
        check_call(["git", "push", "-q"] + force_cmd + ["origin", "tag", tag]) 
開發者ID:acsone,項目名稱:acsoo,代碼行數:25,代碼來源:tag.py

示例9: restore

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def restore(ctx, file: str, allow_nonempty: bool) -> None:
    cargs = ctx.obj['connargs']
    conn = cargs.new_connection()
    dbname = conn.dbname

    try:
        if not is_empty_db(conn) and not allow_nonempty:
            raise click.ClickException(
                f'cannot restore into the {dbname!r} database: '
                f'the database is not empty; '
                f'consider using the --allow-nonempty option'
            )

        restorer = restoremod.RestoreImpl()
        restorer.restore(conn, file)
    finally:
        conn.close() 
開發者ID:edgedb,項目名稱:edgedb,代碼行數:19,代碼來源:__init__.py

示例10: cli

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def cli(ctx, project_id, verbose, api_endpoint, credentials):
    try:
        with open(credentials, 'r') as f:
            c = google.oauth2.credentials.Credentials(token=None,
                                                      **json.load(f))
            http_request = google.auth.transport.requests.Request()
            c.refresh(http_request)
    except Exception as e:
        raise click.ClickException('Error loading credentials: %s.\n'
                                   'Run google-oauthlib-tool to initialize '
                                   'new OAuth 2.0 credentials.' % e)
    ctx.obj['API_ENDPOINT'] = api_endpoint
    ctx.obj['API_VERSION'] = ASSISTANT_API_VERSION
    ctx.obj['SESSION'] = None
    ctx.obj['PROJECT_ID'] = project_id
    ctx.obj['CREDENTIALS'] = c
    if verbose:
        logging.getLogger().setLevel(logging.DEBUG) 
開發者ID:googlesamples,項目名稱:assistant-sdk-python,代碼行數:20,代碼來源:devicetool.py

示例11: parquet

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def parquet(tables, data_directory, ignore_missing_dependency, **params):
    try:
        import pyarrow as pa  # noqa: F401
        import pyarrow.parquet as pq  # noqa: F401
    except ImportError:
        msg = 'PyArrow dependency is missing'
        if ignore_missing_dependency:
            logger.warning('Ignored: %s', msg)
            return 0
        else:
            raise click.ClickException(msg)

    data_directory = Path(data_directory)
    for table, df in read_tables(tables, data_directory):
        arrow_table = pa.Table.from_pandas(df)
        target_path = data_directory / '{}.parquet'.format(table)
        pq.write_table(arrow_table, str(target_path)) 
開發者ID:ibis-project,項目名稱:ibis,代碼行數:19,代碼來源:datamgr.py

示例12: templates

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def templates(ctx, template_type, name, export_file):
    """
    Export templates to file
    """
    vmanage_files = Files(ctx.auth, ctx.host)

    if template_type == 'device':
        if name:
            click.echo(f'Exporting device template(s) {",".join(name)} to {export_file}')
            vmanage_files.export_templates_to_file(export_file, name_list=name, template_type='device')
        else:
            click.echo(f'Exporting device templates to {export_file}')
            vmanage_files.export_templates_to_file(export_file, template_type='device')
    elif template_type == 'feature':
        if name:
            click.echo(f'Exporting feature template(s) {",".join(name)} to {export_file}')
            vmanage_files.export_templates_to_file(export_file, name_list=name, template_type='feature')
        else:
            click.echo(f'Exporting feature templates to {export_file}')
            vmanage_files.export_templates_to_file(export_file, template_type='feature')
    else:
        if name:
            raise click.ClickException("Must specify template type with name")
        click.echo(f'Exporting templates to {export_file}')
        vmanage_files.export_templates_to_file(export_file) 
開發者ID:CiscoDevNet,項目名稱:python-viptela,代碼行數:27,代碼來源:templates.py

示例13: build

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def build(ctx, source, nowarn):
    """
    Build documentation from ``source``, placing built files in
    ``target``.
    """
    _logger.info('building documentation')
    outdir = ctx.obj['outdir']

    if sphinx_version_at_least_1_7:
        # args have to be specified this way for 1.7+, otherwise one gets
        # "Builder name  html not registered or available through entry point"
        # See https://github.com/sphinx-doc/sphinx/issues/4623
        args = ['-b', 'html']
    else:
        args = ['-b html']

    if not nowarn:
        args.append('-W')
    if build_main(args + [source, outdir]):
        raise click.ClickException("Error building sphinx doc") 
開發者ID:Syntaf,項目名稱:travis-sphinx,代碼行數:22,代碼來源:build.py

示例14: verify

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def verify(subvol, manifest):
    if os.getuid():
        raise click.ClickException("Run as root or use sudo")
    if not manifest:
        manifest = "/var/lib/butterknife/manifests/%s" % subvol

    if not subvol:
        raise click.ClickException("Failed to determine template corresponding to root filesystem, try specifying particular template to verify")

    click.echo("Verifying %s" % subvol)

    if subvol.endswith("/"):
        subvol = subvol[:-1]
    if not subvol.startswith("/"):
        subvol = os.path.join("/var/lib/butterknife/pool", subvol)

    verify_manifest(subvol) # This will raise exceptions
    click.echo("Verification successful") 
開發者ID:laurivosandi,項目名稱:butterknife,代碼行數:20,代碼來源:cli.py

示例15: main

# 需要導入模塊: import click [as 別名]
# 或者: from click import ClickException [as 別名]
def main(source):
    """
    For a given command line supplied argument, negotiate the content, parse
    the schema and then return any issues to stdout or if no schema issues,
    return success exit code.
    """
    if source is None:
        click.echo(
            "You need to supply a file or url to a schema to a swagger schema, for"
            "the validator to work."
        )
        return 1
    try:
        load(source)
        click.echo("Validation passed")
        return 0
    except ValidationError as e:
        raise click.ClickException(str(e)) 
開發者ID:pipermerriam,項目名稱:flex,代碼行數:20,代碼來源:cli.py


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