当前位置: 首页>>代码示例>>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;未经允许,请勿转载。