Python click.get_terminal_size() Examples

The following are 30 code examples of click.get_terminal_size(). 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: main.py    From torchgpipe with Apache License 2.0 6 votes vote down vote up
def log(msg: str, clear: bool = False, nl: bool = True) -> None:
    """Prints a message with elapsed time."""
    if clear:
        # Clear the output line to overwrite.
        width, _ = click.get_terminal_size()
        click.echo('\b\r', nl=False)
        click.echo(' ' * width, nl=False)
        click.echo('\b\r', nl=False)

    t = time.time() - BASE_TIME
    h = t // 3600
    t %= 3600
    m = t // 60
    t %= 60
    s = t

    click.echo('%02d:%02d:%02d | ' % (h, m, s), nl=False)
    click.echo(msg, nl=nl) 
Example #2
Source File: cli.py    From guildai with Apache License 2.0 6 votes vote down vote up
def _item_out(item, cols, col_info, detail, indent, max_col_width, err):
    indent_padding = " " * indent
    click.echo(indent_padding, nl=False, err=err)
    line_pos = indent
    for i, col in enumerate(cols):
        val = item[col]
        last_col = i == len(cols) - 1
        val = _pad_col_val(val, col, col_info) if not last_col else val
        line_pos = line_pos + len(val)
        if line_pos > max_col_width:
            click.echo(val[: -(line_pos - max_col_width)], nl=False, err=err)
            break
        else:
            click.echo(val, nl=False, err=err)
    click.echo(err=err)
    terminal_width = click.get_terminal_size()[0]
    for key in detail or []:
        click.echo(indent_padding, nl=False, err=err)
        formatted = _format_detail_val(item[key], indent, terminal_width)
        click.echo("  %s:%s" % (key, formatted), err=err) 
Example #3
Source File: resources.py    From apio with GNU General Public License v2.0 6 votes vote down vote up
def list_fpgas(self):
        """Return a list with all the supported FPGAs"""

        # Print table
        click.echo('\nSupported FPGAs:\n')

        FPGALIST_TPL = ('{fpga:40} {arch:<8} {type:<12} {size:<5} {pack:<10}')
        terminal_width, _ = click.get_terminal_size()

        click.echo('-' * terminal_width)
        click.echo(FPGALIST_TPL.format(
            fpga=click.style('FPGA', fg='cyan'), type='Type', arch='Arch',
            size='Size', pack='Pack'))
        click.echo('-' * terminal_width)

        for fpga in self.fpgas:
            click.echo(FPGALIST_TPL.format(
                fpga=click.style(fpga, fg='cyan'),
                arch=self.fpgas.get(fpga).get('arch'),
                type=self.fpgas.get(fpga).get('type'),
                size=self.fpgas.get(fpga).get('size'),
                pack=self.fpgas.get(fpga).get('pack'))) 
Example #4
Source File: main.py    From torchgpipe with Apache License 2.0 6 votes vote down vote up
def log(msg: str, clear: bool = False, nl: bool = True) -> None:
    """Prints a message with elapsed time."""
    if clear:
        # Clear the output line to overwrite.
        width, _ = click.get_terminal_size()
        click.echo('\b\r', nl=False)
        click.echo(' ' * width, nl=False)
        click.echo('\b\r', nl=False)

    t = time.time() - BASE_TIME
    h = t // 3600
    t %= 3600
    m = t // 60
    t %= 60
    s = t

    click.echo('%02d:%02d:%02d | ' % (h, m, s), nl=False)
    click.echo(msg, nl=nl) 
Example #5
Source File: cum.py    From cum with Apache License 2.0 6 votes vote down vote up
def chapters(alias):
    """List all chapters for a manga series.

    Chapter listing will contain the flag value for the chapter ('n' for new,
    'i' for ignored and blank for downloaded), the chapter identifier ("chapter
    number") and the possible chapter title and group.
    """
    s = db.Series.alias_lookup(alias)
    if s.chapters:
        click.secho('f  chapter  title [group]', bold=True)
        for chapter in s.ordered_chapters:
            name_len = click.get_terminal_size()[0] - 11
            name = '{} {}'.format(chapter.title, chapter.group_tag)[:name_len]
            row = '{}  {:>7}  {}'.format(chapter.status, chapter.chapter, name)
            if row[0] == 'n':
                style = {'fg': 'white', 'bold': True}
            elif row[0] == ' ':
                style = {'bold': True}
            else:
                style = {}
            click.secho(row, **style) 
Example #6
Source File: output.py    From cum with Apache License 2.0 6 votes vote down vote up
def list(items):
    """Print out a list of items in columns much like `ls` in bash."""
    if items:
        width = click.get_terminal_size()[0]
        longest = len(max(items, key=len))
        columns = int(width // (longest + 0.5))
        rows = ceil(len(items) / columns)

        for row in range(rows):
            line = []
            for column in range(columns):
                i = rows * column + row
                if i >= len(items):
                    continue
                line.append(items[i].ljust(longest))
            click.echo(' '.join(line)) 
Example #7
Source File: output.py    From cum with Apache License 2.0 6 votes vote down vote up
def even_columns(items, bold_first_column=False, separator_width=1):
    """Prints two columns with the second column padded so that it always
    begins on the same line, regardless of how long the first column is on the
    same line. Takes input as a list of two item tuples.
    """
    first_column_length = len(max([x[0] for x in items], key=len))
    for item in items:
        padding = first_column_length - len(item[0])
        separator = ' ' * separator_width
        first_column = click.style(item[0] + ' ' * padding,
                                   bold=bold_first_column)
        indent = len(item[0]) + padding + separator_width
        line = click.wrap_text(separator.join([first_column, item[1]]),
                               subsequent_indent=' ' * indent,
                               width=click.get_terminal_size()[0])
        click.echo(line) 
Example #8
Source File: run.py    From web2board with GNU Lesser General Public License v3.0 6 votes vote down vote up
def process(self):
        terminal_width, _ = click.get_terminal_size()
        start_time = time()

        click.echo("[%s] Processing %s (%s)" % (
            datetime.now().strftime("%c"),
            click.style(self.name, fg="cyan", bold=True),
            ", ".join(["%s: %s" % (k, v) for k, v in self.options.iteritems()])
        ))
        click.secho("-" * terminal_width, bold=True)

        result = self._run()

        is_error = result['returncode'] != 0
        summary_text = " Took %.2f seconds " % (time() - start_time)
        half_line = "=" * ((terminal_width - len(summary_text) - 10) / 2)
        click.echo("%s [%s]%s%s" % (
            half_line,
            (click.style(" ERROR ", fg="red", bold=True)
             if is_error else click.style("SUCCESS", fg="green", bold=True)),
            summary_text,
            half_line
        ), err=is_error)

        return not is_error, result # [JORGE_GARCIA] added result to the return for further use 
Example #9
Source File: runner.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def __init__(self, *, stream, verbosity, warnings, tests,
                 output_format=OutputFormat.auto, failfast=False, suite):
        super().__init__(stream, False, verbosity)
        self.verbosity = verbosity
        self.catch_warnings = warnings
        self.failfast = failfast
        self.test_stats = []
        self.warnings = []
        self.notImplemented = []
        self.currently_running = {}
        # An index of all seen warnings to keep track
        # of repeated warnings.
        self._warnings = {}
        self.suite = suite

        if (output_format is OutputFormat.verbose or
                (output_format is OutputFormat.auto and self.verbosity > 1)):
            self.ren = VerboseRenderer(tests=tests, stream=stream)
        elif (output_format is OutputFormat.stacked or
                (output_format is OutputFormat.auto and stream.isatty() and
                 click.get_terminal_size()[0] > 60 and
                 os.name != 'nt')):
            self.ren = MultiLineRenderer(tests=tests, stream=stream)
        else:
            self.ren = SimpleRenderer(tests=tests, stream=stream) 
Example #10
Source File: main.py    From torchgpipe with Apache License 2.0 6 votes vote down vote up
def log(msg: str, clear: bool = False, nl: bool = True) -> None:
    """Prints a message with elapsed time."""
    if clear:
        # Clear the output line to overwrite.
        width, _ = click.get_terminal_size()
        click.echo('\b\r', nl=False)
        click.echo(' ' * width, nl=False)
        click.echo('\b\r', nl=False)

    t = time.time() - BASE_TIME
    h = t // 3600
    t %= 3600
    m = t // 60
    t %= 60
    s = t

    click.echo('%02d:%02d:%02d | ' % (h, m, s), nl=False)
    click.echo(msg, nl=nl) 
Example #11
Source File: main.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_reserved_space(self):
        """Get the number of lines to reserve for the completion menu."""
        reserved_space_ratio = 0.45
        max_reserved_space = 8
        _, height = click.get_terminal_size()
        return min(int(round(height * reserved_space_ratio)), max_reserved_space) 
Example #12
Source File: main.py    From torchgpipe with Apache License 2.0 5 votes vote down vote up
def hr() -> None:
    """Prints a horizontal line."""
    width, _ = click.get_terminal_size()
    click.echo('-' * width) 
Example #13
Source File: main.py    From torchgpipe with Apache License 2.0 5 votes vote down vote up
def hr() -> None:
    """Prints a horizontal line."""
    width, _ = click.get_terminal_size()
    click.echo('-' * width) 
Example #14
Source File: main.py    From torchgpipe with Apache License 2.0 5 votes vote down vote up
def hr() -> None:
    """Prints a horizontal line."""
    width, _ = click.get_terminal_size()
    click.echo('-' * width) 
Example #15
Source File: main.py    From torchgpipe with Apache License 2.0 5 votes vote down vote up
def hr() -> None:
    """Prints a horizontal line."""
    width, _ = click.get_terminal_size()
    click.echo('-' * width) 
Example #16
Source File: main.py    From torchgpipe with Apache License 2.0 5 votes vote down vote up
def hr() -> None:
    """Prints a horizontal line."""
    width, _ = click.get_terminal_size()
    click.echo('-' * width) 
Example #17
Source File: main.py    From torchgpipe with Apache License 2.0 5 votes vote down vote up
def hr() -> None:
    """Prints a horizontal line."""
    width, _ = click.get_terminal_size()
    click.echo('-' * width) 
Example #18
Source File: utility.py    From cum with Apache License 2.0 5 votes vote down vote up
def print_new_normal(items):
    """Prints the new chapter information. E.g.
        joukamachi-no-dandelion
        30  31  32  33  34
        minami-ke
        153  154  155  156  157
    """
    width = click.get_terminal_size()[0]
    for series in items:
        click.secho(series[0], bold=True)
        click.echo(click.wrap_text(series[1], width=width)) 
Example #19
Source File: test_main.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reserved_space_is_integer():
    """Make sure that reserved space is returned as an integer."""

    def stub_terminal_size():
        return (5, 5)

    old_func = click.get_terminal_size

    click.get_terminal_size = stub_terminal_size
    lc = LiteCli()
    assert isinstance(lc.get_reserved_space(), int)
    click.get_terminal_size = old_func 
Example #20
Source File: server_config_check.py    From nichtparasoup with MIT License 5 votes vote down vote up
def print_probed_erroneous(probe_results: ConfigProbeResults) -> None:  # pragma: no cover
    echo()
    ex_formatter = Formatter()
    term_width = get_terminal_size()[0]
    for probed in filter(lambda probed: probed.result.is_erroneous, probe_results):
        error_color = _COLOR_FAILURE if probed.result.is_failure else _COLOR_WARNING
        result_type = 'ERROR' if probed.result.is_failure else 'WARNING'
        for error_num, error in enumerate(probed.result.errors):
            line_delimiter = '-' if error_num > 0 else '='
            echo(style(f' {result_type}: {probed.imagecrawler} '.center(term_width, line_delimiter), fg=error_color),
                 err=True)
            echo(style(str(error), fg=error_color), err=True)
            echo(ex_formatter.formatException((type(error), error, error.__traceback__)), err=True) 
Example #21
Source File: server_config_check.py    From nichtparasoup with MIT License 5 votes vote down vote up
def print_probed_summary(probe_results: ConfigProbeResults, *,
                         elapsed_seconds: Optional[Union[int, float]]
                         ) -> None:  # pragma: no cover
    summary: Dict[_ProbedSummaryType, _ProbedSummaryCounter] = {
        _ProbedSummaryType.failed: _ProbedSummaryCounter(
            _COLOR_FAILURE,
            len([None for probed in probe_results if probed.result.is_failure])
        ),
        _ProbedSummaryType.passed: _ProbedSummaryCounter(
            _COLOR_SUCCESS,
            len([None for probed in probe_results if not probed.result.is_failure])
        ),
        _ProbedSummaryType.warned: _ProbedSummaryCounter(
            _COLOR_WARNING,
            len([None for probed in probe_results if not probed.result.is_failure and probed.result.is_erroneous])
        ),
    }
    overall_result = _ProbedSummaryType.failed \
        if summary[_ProbedSummaryType.failed].value > 0 \
        else _ProbedSummaryType.passed
    summary_color = summary[overall_result].color
    summary_string_spacer = ' '
    summary_string = summary_string_spacer + ', '.join(
        style(f'{counter.value} {counter_type.value}', fg=counter.color, bold=counter_type == overall_result)
        for counter_type, counter
        in summary.items()
        if counter.value > 0
    ) + summary_string_spacer
    if elapsed_seconds is not None:
        summary_string += style(f'in {elapsed_seconds:.2f}s', fg=summary_color) + summary_string_spacer
    summary_width = len(unstyle(summary_string))
    term_width = get_terminal_size()[0]
    line_width = max(0, term_width - summary_width)
    line_width_first_half = line_width // 2
    echo(''.join([
        style('=' * line_width_first_half, fg=summary_color) if line_width_first_half else '',
        summary_string,
        style('=' * (line_width - line_width_first_half), fg=summary_color) if line_width_first_half else '',
    ]), err=True) 
Example #22
Source File: main.py    From athenacli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_reserved_space(self):
        """Get the number of lines to reserve for the completion menu."""
        reserved_space_ratio = .45
        max_reserved_space = 8
        _, height = click.get_terminal_size()
        return min(int(round(height * reserved_space_ratio)), max_reserved_space) 
Example #23
Source File: display.py    From gtd.py with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def resize_and_get_table(self, table, fields, sort):
        '''Remove columns from the table until it fits in your terminal'''
        maxwidth = click.get_terminal_size()[0]
        possible = table.get_string(fields=fields, sortby=sort)
        fset = set(fields)
        # Fields in increasing order of importance
        to_remove = ['desc', 'id', 'url', 'activity', 'list']
        # Wait until we're under max width or until we can't discard more fields
        while len(possible.splitlines()[0]) >= maxwidth and to_remove:
            # Remove a field one at a time
            fset.remove(to_remove.pop(0))
            possible = table.get_string(fields=list(fset), sortby=sort)
        return possible 
Example #24
Source File: cli.py    From pyfx with MIT License 5 votes vote down vote up
def hr(char='-', width=None, **kwargs):
    if width is None:
        width = click.get_terminal_size()[0]
    click.secho(char * width, **kwargs) 
Example #25
Source File: ssh.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _set_columns():
        w, _h = click.get_terminal_size()
        return ["export COLUMNS=%i" % w] 
Example #26
Source File: cli.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _max_width():
    try:
        return int(os.environ["COLUMNS"])
    except (KeyError, ValueError):
        return click.get_terminal_size()[0] 
Example #27
Source File: cli.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _wrap(s):
    terminal_width = click.get_terminal_size()[0]
    width = max(min(terminal_width, 78), 40)
    return click.wrap_text(s, width) 
Example #28
Source File: base.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def update_progress(cls, progress, starttime):
        """ Display an ascii progress bar while processing operation. """
        width, _height = click.get_terminal_size()
        if not width:
            return

        duration = datetime.utcnow() - starttime
        hours, remainder = divmod(duration.seconds, 3600)
        minutes, seconds = divmod(remainder, 60)

        size = int(width * .6)
        status = ""
        if isinstance(progress, int):
            progress = float(progress)
        if not isinstance(progress, float):
            progress = 0
            status = 'error: progress var must be float\n'
            cls.echo(type(progress))
        if progress < 0:
            progress = 0
            status = 'Halt...\n'
        if progress >= 1:
            progress = 1
            # status = 'Done...\n'
        block = int(round(size * progress))
        text = ('\rProgress: [{0}] {1:.2%} {2} {3:0>2}:{4:0>2}:{5:0>2}  '
                ''.format('#' * block + '-' * (size - block), progress,
                          status, hours, minutes, seconds))
        sys.stdout.write(text)
        sys.stdout.flush() 
Example #29
Source File: platforms.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def platforms_search(query, json_output):

    data = []
    platforms = PlatformFactory.get_platforms().keys()
    platforms.sort()
    for platform in platforms:
        p = PlatformFactory.newPlatform(platform)
        type_ = p.get_type()
        description = p.get_description()

        if query == "all":
            query = ""

        search_data = "%s %s %s" % (type_, description, p.get_packages())
        if query and query.lower() not in search_data.lower():
            continue

        data.append({
            "type": type_,
            "description": description,
            "packages": p.get_packages()
        })

    if json_output:
        click.echo(json.dumps(data))
    else:
        terminal_width, _ = click.get_terminal_size()
        for item in data:
            click.secho(item['type'], fg="cyan", nl=False)
            click.echo(" (available packages: %s)" % ", ".join(
                item.get("packages").keys()))
            click.echo("-" * terminal_width)
            click.echo(item['description'])
            click.echo() 
Example #30
Source File: formatter.py    From pygreynoise with MIT License 5 votes vote down vote up
def analyze_formatter(result, verbose):
    """Conver analyze result into human-readable text."""
    template = JINJA2_ENV.get_template("analyze.txt.j2")
    max_width, _ = click.get_terminal_size()
    return template.render(result=result, verbose=verbose, max_width=max_width)