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


Python click.open_file方法代碼示例

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


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

示例1: analyze

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def analyze(
    context, api_client, api_key, input_file, output_file, output_format, verbose
):
    """Analyze the IP addresses in a log file, stdin, etc."""
    if input_file is None:
        if sys.stdin.isatty():
            output = [
                context.command.get_usage(context),
                (
                    "Error: at least one text file must be passed "
                    "either through the -i/--input_file option or through a shell pipe."
                ),
            ]
            click.echo("\n\n".join(output))
            context.exit(-1)
        else:
            input_file = click.open_file("-")
    if output_file is None:
        output_file = click.open_file("-", mode="w")

    result = api_client.analyze(input_file)
    return result 
開發者ID:GreyNoise-Intelligence,項目名稱:pygreynoise,代碼行數:24,代碼來源:subcommand.py

示例2: filter

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def filter(context, api_client, api_key, input_file, output_file, noise_only):
    """Filter the noise from a log file, stdin, etc."""
    if input_file is None:
        if sys.stdin.isatty():
            output = [
                context.command.get_usage(context),
                (
                    "Error: at least one text file must be passed "
                    "either through the -i/--input_file option or through a shell pipe."
                ),
            ]
            click.echo("\n\n".join(output))
            context.exit(-1)
        else:
            input_file = click.open_file("-")
    if output_file is None:
        output_file = click.open_file("-", mode="w")

    for chunk in api_client.filter(input_file, noise_only=noise_only):
        output_file.write(ANSI_MARKUP(chunk)) 
開發者ID:GreyNoise-Intelligence,項目名稱:pygreynoise,代碼行數:22,代碼來源:subcommand.py

示例3: synthesize

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [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

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def list(ctx, output):
    """List datasets.

    Prints a list of objects describing datasets.

        $ mapbox datasets list

    All endpoints require authentication. An access token with
    `datasets:read` scope is required, see `mapbox --help`.
    """

    stdout = click.open_file(output, 'w')
    service = ctx.obj.get('service')
    res = service.list()

    if res.status_code == 200:
        click.echo(res.text, file=stdout)
    else:
        raise MapboxCLIException(res.text.strip()) 
開發者ID:mapbox,項目名稱:mapbox-cli-py,代碼行數:21,代碼來源:datasets.py

示例5: read_dataset

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def read_dataset(ctx, dataset, output):
    """Read the attributes of a dataset.

    Prints a JSON object containing the attributes
    of a dataset. The attributes: owner (a Mapbox account),
    id (dataset id), created (Unix timestamp), modified
    (timestamp), name (string), and description (string).

        $ mapbox datasets read-dataset dataset-id

    All endpoints require authentication. An access token with
    `datasets:read` scope is required, see `mapbox --help`.
    """

    stdout = click.open_file(output, 'w')
    service = ctx.obj.get('service')
    res = service.read_dataset(dataset)

    if res.status_code == 200:
        click.echo(res.text, file=stdout)
    else:
        raise MapboxCLIException(res.text.strip()) 
開發者ID:mapbox,項目名稱:mapbox-cli-py,代碼行數:24,代碼來源:datasets.py

示例6: list_features

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def list_features(ctx, dataset, reverse, start, limit, output):
    """Get features of a dataset.

    Prints the features of the dataset as a GeoJSON feature collection.

        $ mapbox datasets list-features dataset-id

    All endpoints require authentication. An access token with
    `datasets:read` scope is required, see `mapbox --help`.
    """

    stdout = click.open_file(output, 'w')
    service = ctx.obj.get('service')
    res = service.list_features(dataset, reverse, start, limit)

    if res.status_code == 200:
        click.echo(res.text, file=stdout)
    else:
        raise MapboxCLIException(res.text.strip()) 
開發者ID:mapbox,項目名稱:mapbox-cli-py,代碼行數:21,代碼來源:datasets.py

示例7: read_feature

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def read_feature(ctx, dataset, fid, output):
    """Read a dataset feature.

    Prints a GeoJSON representation of the feature.

        $ mapbox datasets read-feature dataset-id feature-id

    All endpoints require authentication. An access token with
    `datasets:read` scope is required, see `mapbox --help`.
    """

    stdout = click.open_file(output, 'w')
    service = ctx.obj.get('service')
    res = service.read_feature(dataset, fid)

    if res.status_code == 200:
        click.echo(res.text, file=stdout)
    else:
        raise MapboxCLIException(res.text.strip()) 
開發者ID:mapbox,項目名稱:mapbox-cli-py,代碼行數:21,代碼來源:datasets.py

示例8: idzip_compression

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def idzip_compression(path, output):
        '''Compress a file using  idzip, a gzip-compatible format with random access support.
        '''
        if output is None:
            output = '-'
        with click.open_file(output, mode='wb') as outfh:
            writer = _compression.GzipFile(fileobj=outfh, mode='wb')
            with click.open_file(path, 'rb') as infh:
                try:
                    infh_wrap = io.BufferedReader(infh)
                    header = infh_wrap.peek(2)
                    if _compression.starts_with_gz_magic(header):
                        click.echo("Detected gzip input file", err=True)
                        infh_wrap = _compression.GzipFile(fileobj=infh_wrap)
                except AttributeError:
                    infh_wrap = infh
                buffer_size = _compression.WRITE_BUFFER_SIZE
                chunk = infh_wrap.read(buffer_size)
                while chunk:
                    writer.write(chunk)
                    chunk = infh_wrap.read(buffer_size)
            writer.close() 
開發者ID:mobiusklein,項目名稱:ms_deisotope,代碼行數:24,代碼來源:indexing.py

示例9: save_cmd

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def save_cmd(filename, indent, textures):
    """Save the city model to a CityJSON file."""
    def processor(cm):
        print_cmd_status("Saving CityJSON to a file (%s)" % (filename))
        f = os.path.basename(filename)
        d = os.path.abspath(os.path.dirname(filename))
        if not os.path.isdir(d):
            os.makedirs(d)
        p = os.path.join(d, f)
        try:
            fo = click.open_file(p, mode='w')
            if textures:
                cm.copy_textures(textures, p)
            if indent == 0:
                json_str = json.dumps(cm.j, separators=(',',':'))
                fo.write(json_str)
            else:
                json_str = json.dumps(cm.j, indent=indent)
                fo.write(json_str)
        except IOError as e:
            raise click.ClickException('Invalid output file: "%s".\n%s' % (p, e))                
        return cm
    return processor 
開發者ID:cityjson,項目名稱:cjio,代碼行數:25,代碼來源:cjio.py

示例10: rename

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def rename(workspace, output_file, channel, sample, modifier, measurement):
    """
    Rename components of the workspace.

    See :func:`pyhf.workspace.Workspace.rename` for more information.
    """
    with click.open_file(workspace, 'r') as specstream:
        spec = json.load(specstream)

    ws = Workspace(spec)
    renamed_ws = ws.rename(
        channels=dict(channel),
        samples=dict(sample),
        modifiers=dict(modifier),
        measurements=dict(measurement),
    )

    if output_file is None:
        click.echo(json.dumps(renamed_ws, indent=4, sort_keys=True))
    else:
        with open(output_file, 'w+') as out_file:
            json.dump(renamed_ws, out_file, indent=4, sort_keys=True)
        log.debug("Written to {0:s}".format(output_file)) 
開發者ID:scikit-hep,項目名稱:pyhf,代碼行數:25,代碼來源:spec.py

示例11: combine

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def combine(workspace_one, workspace_two, join, output_file):
    """
    Combine two workspaces into a single workspace.

    See :func:`pyhf.workspace.Workspace.combine` for more information.
    """
    with click.open_file(workspace_one, 'r') as specstream:
        spec_one = json.load(specstream)

    with click.open_file(workspace_two, 'r') as specstream:
        spec_two = json.load(specstream)

    ws_one = Workspace(spec_one)
    ws_two = Workspace(spec_two)
    combined_ws = Workspace.combine(ws_one, ws_two, join=join)

    if output_file is None:
        click.echo(json.dumps(combined_ws, indent=4, sort_keys=True))
    else:
        with open(output_file, 'w+') as out_file:
            json.dump(combined_ws, out_file, indent=4, sort_keys=True)
        log.debug("Written to {0:s}".format(output_file)) 
開發者ID:scikit-hep,項目名稱:pyhf,代碼行數:24,代碼來源:spec.py

示例12: verify

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def verify(background_only, patchset):
    """
    Verify the patchset digests against a background-only workspace specification. Verified if no exception was raised.

    Raises:
        :class:`~pyhf.exceptions.PatchSetVerificationError`: if the patchset cannot be verified against the workspace specification

    Returns:
        None
    """
    with click.open_file(background_only, 'r') as specstream:
        spec = json.load(specstream)

    ws = Workspace(spec)

    with click.open_file(patchset, 'r') as fstream:
        patchset_spec = json.load(fstream)

    patchset = PatchSet(patchset_spec)
    patchset.verify(ws)

    click.echo("All good.") 
開發者ID:scikit-hep,項目名稱:pyhf,代碼行數:24,代碼來源:patchset.py

示例13: do_invoke

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def do_invoke(template, namespace, function, env_vars, event, no_event, debug_port, debug_args, quiet):
    if no_event:
        event_data = "{}"
    else:
        Operation('Enter an event:', color="green").echo()
        with click.open_file(event, 'r', encoding="utf-8") as f:
            event_data = f.read()
    try:
        with InvokeContext(
                template_file=template,
                namespace=namespace,
                function=function,
                env_file=env_vars,
                debug_port=debug_port,
                debug_args=debug_args,
                event=event_data,
                is_quiet=quiet
        ) as context:
            context.invoke()
    except Exception as e:
        Operation(e, err_msg=traceback.format_exc(), level="ERROR").no_output()
        raise e 
開發者ID:tencentyun,項目名稱:scfcli,代碼行數:24,代碼來源:cli.py

示例14: append_errors_to_file

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def append_errors_to_file(filename:str, errors:List[Error], time) -> None:
    """
    Creates a single file that logs all errors
    """
    dirname = os.path.dirname(filename)
    if dirname != '':
        os.makedirs(dirname, exist_ok=True)

    with click.open_file(filename, 'a+') as f:
        f.write('--- {} ---\n'.format(time))

        for e in errors:
            if isinstance(e, NodeError):
                f.write('node({})\t{}\n'.format(e.node, e.message))
            elif isinstance(e, EdgeError):
                f.write('edge({}, {})\t{}\n'.format(e.subject, e.object, e.message))
            else:
                raise Exception('Expected type {} but got: {}'.format(Error, type(error)))

        click.echo('Logged {} errors to {}'.format(len(errors), filename)) 
開發者ID:NCATS-Tangerine,項目名稱:kgx,代碼行數:22,代碼來源:error_logging.py

示例15: write_output_file

# 需要導入模塊: import click [as 別名]
# 或者: from click import open_file [as 別名]
def write_output_file(config, domains_combined):
    config_dict = make_config_dict()

    leprint("Writing output file: %s in %s format", config.output, config.mode,
           level=LOG['INFO'])
    with click.open_file(config.output, 'wb', atomic=True, lazy=True) as fh:
        fh.write(make_output_file_header(config_dict))
        for domain in domains_combined:
            if config.mode == 'dnsmasq':
                if config.dest_ip:
                    dnsmasq_line = 'address=/.' + domain.decode('utf8') + \
                                   '/' + config.dest_ip + '\n'
                else:
                    dnsmasq_line = 'server=/.' + domain.decode('utf8') + \
                                   '/' '\n'  # return NXDOMAIN
                fh.write(dnsmasq_line.encode('utf8'))
            elif config.mode == 'hosts':
                if config.dest_ip:
                    hosts_line = config.dest_ip + ' ' + domain.decode('utf8') + '\n'
                else:
                    hosts_line = '127.0.0.1' + ' ' + domain.decode('utf8') + '\n'
                fh.write(hosts_line.encode('utf8')) 
開發者ID:jakeogh,項目名稱:dnsgate,代碼行數:24,代碼來源:dnsgate.py


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