Python click.get_binary_stream() Examples

The following are 10 code examples of click.get_binary_stream(). 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: cli.py    From pygeobuf with ISC License 6 votes vote down vote up
def encode(precision, with_z):
    """Given GeoJSON on stdin, writes a geobuf file to stdout."""
    logger = logging.getLogger('geobuf')
    stdin = click.get_text_stream('stdin')
    sink = click.get_binary_stream('stdout')
    try:
        data = json.load(stdin)
        pbf = geobuf.encode(
            data,
            precision if precision >= 0 else 6,
            3 if with_z else 2)
        sink.write(pbf)
        sys.exit(0)
    except Exception:
        logger.exception("Failed. Exception caught")
        sys.exit(1) 
Example #2
Source File: cli.py    From pygeobuf with ISC License 5 votes vote down vote up
def decode():
    """Given a Geobuf byte string on stdin, write a GeoJSON feature
    collection to stdout."""
    logger = logging.getLogger('geobuf')
    stdin = click.get_binary_stream('stdin')
    sink = click.get_text_stream('stdout')
    try:
        pbf = stdin.read()
        data = geobuf.decode(pbf)
        json.dump(data, sink)
        sys.exit(0)
    except Exception:
        logger.exception("Failed. Exception caught")
        sys.exit(1) 
Example #3
Source File: cli.py    From chinese-support-redux with GNU General Public License v3.0 5 votes vote down vote up
def tts_cli(text, file, output, slow, lang, nocheck):
    """ Read <text> to mp3 format using Google Translate's Text-to-Speech API
    (set <text> or --file <file> to - for standard input)
    """

    # stdin for <text>
    if text == '-':
        text = click.get_text_stream('stdin').read()

    # stdout (when no <output>)
    if not output:
        output = click.get_binary_stream('stdout')

    # <file> input (stdin on '-' is handled by click.File)
    if file:
        try:
            text = file.read()
        except UnicodeDecodeError as e:  # pragma: no cover
            log.debug(str(e), exc_info=True)
            raise click.FileError(
                file.name,
                "<file> must be encoded using '%s'." %
                sys_encoding())

    # TTS
    try:
        tts = gTTS(
            text=text,
            lang=lang,
            slow=slow,
            lang_check=not nocheck)
        tts.write_to_fp(output)
    except (ValueError, AssertionError) as e:
        raise click.UsageError(str(e))
    except gTTSError as e:
        raise click.ClickException(str(e)) 
Example #4
Source File: datamgr.py    From ibis with Apache License 2.0 5 votes vote down vote up
def download(repo_url, directory):
    from plumbum.cmd import curl
    from shutil import rmtree

    directory = Path(directory)
    # download the master branch
    url = repo_url + '/archive/master.zip'
    # download the zip next to the target directory with the same name
    path = directory.with_suffix('.zip')

    if not path.exists():
        logger.info('Downloading {} to {}...'.format(url, path))
        path.parent.mkdir(parents=True, exist_ok=True)
        download = curl[url, '-o', path, '-L']
        download(
            stdout=click.get_binary_stream('stdout'),
            stderr=click.get_binary_stream('stderr'),
        )
    else:
        logger.info('Skipping download: {} already exists'.format(path))

    logger.info('Extracting archive to {}'.format(directory))

    # extract all files
    extract_to = directory.with_name(directory.name + '_extracted')
    with zipfile.ZipFile(str(path), 'r') as f:
        f.extractall(str(extract_to))

    # remove existent folder
    if directory.exists():
        rmtree(str(directory))

    # rename to the target directory
    (extract_to / 'testing-data-master').rename(directory)

    # remove temporary extraction folder
    extract_to.rmdir() 
Example #5
Source File: feedstock.py    From ibis with Apache License 2.0 5 votes vote down vote up
def clone(repo_uri, destination, branch):
    if not Path(destination).exists():
        cmd = git['clone', repo_uri, destination]
        cmd(
            stdout=click.get_binary_stream('stdout'),
            stderr=click.get_binary_stream('stderr'),
        )

    cmd = git['-C', destination, 'checkout', branch]
    cmd(
        stdout=click.get_binary_stream('stdout'),
        stderr=click.get_binary_stream('stderr'),
    ) 
Example #6
Source File: feedstock.py    From ibis with Apache License 2.0 5 votes vote down vote up
def build(recipe, python):
    click.echo('Building {} recipe...'.format(recipe))

    cmd = conda[
        'build', '--channel', 'conda-forge', '--python', python, recipe
    ]

    cmd(
        stdout=click.get_binary_stream('stdout'),
        stderr=click.get_binary_stream('stderr'),
    ) 
Example #7
Source File: feedstock.py    From ibis with Apache License 2.0 5 votes vote down vote up
def deploy(package_location, artifact_directory, architecture):
    artifact_dir = Path(artifact_directory)
    artifact_dir.mkdir(parents=True, exist_ok=True)
    package_loc = Path(package_location)
    assert package_loc.exists(), 'Path {} does not exist'.format(package_loc)

    for architecture in (architecture, 'noarch'):
        arch_artifact_directory = str(artifact_dir / architecture)
        arch_package_directory = str(package_loc / architecture)
        shutil.copytree(arch_package_directory, arch_artifact_directory)
    cmd = conda['index', artifact_directory]
    cmd(
        stdout=click.get_binary_stream('stdout'),
        stderr=click.get_binary_stream('stderr'),
    ) 
Example #8
Source File: factory.py    From chalice with Apache License 2.0 5 votes vote down vote up
def create_stdin_reader(self):
        # type: () -> PipeReader
        stream = click.get_binary_stream('stdin')
        reader = PipeReader(stream)
        return reader 
Example #9
Source File: cli.py    From gTTS with MIT License 5 votes vote down vote up
def tts_cli(text, file, output, slow, tld, lang, nocheck):
    """ Read <text> to mp3 format using Google Translate's Text-to-Speech API
    (set <text> or --file <file> to - for standard input)
    """

    # stdin for <text>
    if text == '-':
        text = click.get_text_stream('stdin').read()

    # stdout (when no <output>)
    if not output:
        output = click.get_binary_stream('stdout')

    # <file> input (stdin on '-' is handled by click.File)
    if file:
        try:
            text = file.read()
        except UnicodeDecodeError as e:  # pragma: no cover
            log.debug(str(e), exc_info=True)
            raise click.FileError(
                file.name,
                "<file> must be encoded using '%s'." %
                sys_encoding())

    # TTS
    try:
        tts = gTTS(
            text=text,
            lang=lang,
            slow=slow,
            tld=tld,
            lang_check=not nocheck)
        tts.write_to_fp(output)
    except (ValueError, AssertionError) as e:
        raise click.UsageError(str(e))
    except gTTSError as e:
        raise click.ClickException(str(e)) 
Example #10
Source File: omnihash.py    From omnihash with MIT License 4 votes vote down vote up
def main(click_context, hashmes, s, v, c, f, m, j):
    """
    If there is a file at hashme, read and omnihash that file.
    Elif hashme is a string, omnihash that.
    """

    # Print version and quit
    if v:
        version = pkg_resources.require("omnihash")[0].version
        click.echo(version)
        return

    intialize_plugins()

    results = []
    if not hashmes:
        # If no stdin, just help and quit.
        if not sys.stdin.isatty():
            digesters = make_digesters(None, f, c)
            stdin = click.get_binary_stream('stdin')
            bytechunks = iter(lambda: stdin.read(io.DEFAULT_BUFFER_SIZE), b'')
            if not j:
                click.echo("Hashing " + click.style("standard input", bold=True) + "..", err=True)
            results.append([produce_hashes(bytechunks, digesters, match=m, use_json=j)])
        else:
            print(click_context.get_help())
            return
    else:
        hash_many = len(hashmes) > 1
        for hashme in hashmes:
            result = {}
            digesters = make_digesters(hashme, f, c)
            bytechunks = iterate_bytechunks(hashme, s, j, hash_many)
            if bytechunks:
                result = produce_hashes(bytechunks, digesters, match=m, use_json=j)
            if result:
                result['NAME'] = hashme
                results.append(result)

    if results and j:
        print(json.dumps(results, indent=4, sort_keys=True))


##
# Main Logic
##