Python shutil.get_terminal_size() Examples

The following are code examples for showing how to use shutil.get_terminal_size(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: NiujiaoDebugger   Author: MrSrc   File: test_shutil.py    GNU General Public License v3.0 6 votes vote down vote up
def test_stty_match(self):
        """Check if stty returns the same results ignoring env

        This test will fail if stdin and stdout are connected to
        different terminals with different sizes. Nevertheless, such
        situations should be pretty rare.
        """
        try:
            size = subprocess.check_output(['stty', 'size']).decode().split()
        except (FileNotFoundError, PermissionError,
                subprocess.CalledProcessError):
            self.skipTest("stty invocation failed")
        expected = (int(size[1]), int(size[0])) # reversed order

        with support.EnvironmentVarGuard() as env:
            del env['LINES']
            del env['COLUMNS']
            actual = shutil.get_terminal_size()

        self.assertEqual(expected, actual) 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: test_shutil.py    GNU General Public License v3.0 6 votes vote down vote up
def test_fallback(self):
        with support.EnvironmentVarGuard() as env:
            del env['LINES']
            del env['COLUMNS']

            # sys.__stdout__ has no fileno()
            with support.swap_attr(sys, '__stdout__', None):
                size = shutil.get_terminal_size(fallback=(10, 20))
            self.assertEqual(size.columns, 10)
            self.assertEqual(size.lines, 20)

            # sys.__stdout__ is not a terminal on Unix
            # or fileno() not in (0, 1, 2) on Windows
            with open(os.devnull, 'w') as f, \
                 support.swap_attr(sys, '__stdout__', f):
                size = shutil.get_terminal_size(fallback=(30, 40))
            self.assertEqual(size.columns, 30)
            self.assertEqual(size.lines, 40) 
Example 3
Project: em   Author: nhynes   File: __main__.py    MIT License 6 votes vote down vote up
def show(args, _config, _extra_args):
    """Show details about an experiment."""
    import pickle
    import pprint

    name = args.name

    with shelve.open('.em') as emdb:
        if name not in emdb or name == EM_KEY:
            return _die(E_NO_EXP.format(name))
        for info_name, info_val in sorted(emdb[name].items()):
            if isinstance(info_val, datetime.date):
                info_val = info_val.ctime()
            print(f'{info_name}: {info_val}')

    if not args.opts:
        return

    opts_path = _expath(name, 'run', 'opts.pkl')
    with open(opts_path, 'rb') as f_opts:
        print('\noptions:')
        opts = pickle.load(f_opts)
        cols = shutil.get_terminal_size((80, 20)).columns
        pprint.pprint(vars(opts), indent=2, compact=True, width=cols) 
Example 4
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_format.py    MIT License 6 votes vote down vote up
def test_info_repr(self):
        # GH#21746 For tests inside a terminal (i.e. not CI) we need to detect
        # the terminal size to ensure that we try to print something "too big"
        term_width, term_height = get_terminal_size()

        max_rows = 60
        max_cols = 20 + (max(term_width, 80) - 80) // 4
        # Long
        h, w = max_rows + 1, max_cols - 1
        df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
        assert has_vertically_truncated_repr(df)
        with option_context("display.large_repr", "info"):
            assert has_info_repr(df)

        # Wide
        h, w = max_rows - 1, max_cols + 1
        df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
        assert has_horizontally_truncated_repr(df)
        with option_context(
            "display.large_repr", "info", "display.max_columns", max_cols
        ):
            assert has_info_repr(df) 
Example 5
Project: recruit   Author: Frank-qlu   File: terminal.py    Apache License 2.0 6 votes vote down vote up
def get_terminal_size():
    """
    Detect terminal size and return tuple = (width, height).

    Only to be used when running in a terminal. Note that the IPython notebook,
    IPython zmq frontends, or IDLE do not run in a terminal,
    """
    import platform

    if PY3:
        return shutil.get_terminal_size()

    current_os = platform.system()
    tuple_xy = None
    if current_os == 'Windows':
        tuple_xy = _get_terminal_size_windows()
        if tuple_xy is None:
            tuple_xy = _get_terminal_size_tput()
            # needed for window's python in cygwin's xterm!
    if (current_os == 'Linux' or current_os == 'Darwin' or
            current_os.startswith('CYGWIN')):
        tuple_xy = _get_terminal_size_linux()
    if tuple_xy is None:
        tuple_xy = (80, 25)      # default value
    return tuple_xy 
Example 6
Project: CNN-FRIQA   Author: Bobholamovic   File: utils.py    MIT License 6 votes vote down vote up
def show(self, cur, desc):
        bar_len, _ = shutil.get_terminal_size()
        # The tab between desc and the progress bar should be counted.
        # And the '|'s on both ends be counted, too
        bar_len = bar_len - self.len_with_tabs(desc+'\t') - 2
        bar_len = int(bar_len*0.8)
        cur_pos = int(((cur+1)/self.len)*bar_len)
        cur_bar = '|'+self.pat*cur_pos+' '*(bar_len-cur_pos)+'|'

        disp_str = "{0}\t{1}".format(desc, cur_bar)

        # Clean
        self.write('\033[K')

        if self.show_step and (cur % self.print_freq) == 0:
            self.write(disp_str, new_line=True)
            return

        if (cur+1) < self.len:
            self.write(disp_str)
        else:
            self.write(disp_str, new_line=True)

        self.out_stream.flush() 
Example 7
Project: thamos   Author: thoth-station   File: cli.py    GNU General Public License v3.0 6 votes vote down vote up
def status(analysis_id: str = None, output_format: str = None):
    """Get status of an analysis.

    If ANALYSIS_ID is not provided, there will be used last analysis id, if noted by Thamos.
    """
    if not analysis_id:
        with workdir():
            status_dict = get_status()
    else:
        status_dict = get_status(analysis_id)

    if not output_format or output_format == "table":
        table = Texttable(max_width=get_terminal_size().columns)
        table.set_deco(Texttable.VLINES)
        table.add_rows(list(status_dict.items()), header=False)
        output = table.draw()
    elif output_format == "json":
        output = json.dumps(status_dict, indent=2)
    elif output_format == "yaml":
        output = yaml.safe_dump(status_dict, default_flow_style=False)
    else:
        raise NotImplementedError(f"Unknown output format {output_format}")

    click.echo(output) 
Example 8
Project: qctf-starter-2016   Author: HackerDom   File: payload.py    MIT License 6 votes vote down vote up
def run_animation():
    random.seed(42)

    terminal_size = get_terminal_size()
    gen = MazeGenerator(terminal_size.lines - 2 * MARGIN - 2, terminal_size.columns - 2 * MARGIN)
    gen.generate()

    cur_time = 1
    while True:
        if cur_time % 2 == 0:
            message = 'INFECTING THE NETWORK'
        else:
            message = ''
        message_lines = [message.center(terminal_size.columns), '']

        field_lines = [' ' * MARGIN + ''.join(line) for line in gen.get_field(cur_time)]

        print(RESET + '\n'.join([''] * MARGIN + message_lines + field_lines))

        time.sleep(0.5)
        cur_time += 1 
Example 9
Project: mlbv   Author: kmac   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def get_data(self, wrap=True):
        if wrap:
            terminal_size = shutil.get_terminal_size((80, 40))
            wrap_columns = terminal_size.columns
            if wrap_columns > int(config.CONFIG.parser['info_display_max_columns']):
                wrap_columns = int(config.CONFIG.parser['info_display_max_columns'])
            return '\n'.join([textwrap.fill(x, wrap_columns) for x in ''.join(self.fed).split('\n')])
        return ''.join(self.fed) 
Example 10
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example 11
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 12
Project: StyleGAN   Author: mgmk2   File: flickr_face.py    Apache License 2.0 5 votes vote down vote up
def show_progress(idx, idx_range):
    str_before = 'Load Flickr-Faces-HQ Dataset ['
    str_after = ']'
    columns = shutil.get_terminal_size().columns
    bar_length = columns - (len(str_before) + len(str_after)) - 15
    percent = (idx - idx_range[0]) / (idx_range[1] - idx_range[0])
    progress = round(percent * bar_length)
    sys.stdout.write(
        ('\r' + str_before + '=' * progress +
         '-' * (bar_length - progress) + str_after +
         '{: 4d}% '.format(round(percent * 100))))
    sys.stdout.flush() 
Example 13
Project: Repobot   Author: Desgard   File: terminal.py    MIT License 5 votes vote down vote up
def get_terminal_size(defaultx=80, defaulty=25):
    return _get_terminal_size((defaultx, defaulty)) 
Example 14
Project: Rebaler   Author: rrwick   File: misc.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, prog):
        terminal_width = shutil.get_terminal_size().columns
        os.environ['COLUMNS'] = str(terminal_width)
        max_help_position = min(max(24, terminal_width // 3), 40)
        super().__init__(prog, max_help_position=max_help_position) 
Example 15
Project: JukeBox   Author: gauravsarkar97   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example 16
Project: JukeBox   Author: gauravsarkar97   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 17
Project: binmagic   Author: m57   File: misc.py    GNU General Public License v3.0 5 votes vote down vote up
def print_row():

	for n in range(0, shutil.get_terminal_size((80,20)).columns):
		sys.stdout.write("-")
	sys.stdout.write("\n") 
Example 18
Project: py   Author: pytest-dev   File: terminalwriter.py    MIT License 5 votes vote down vote up
def _getdimensions():
    if py33:
        import shutil
        size = shutil.get_terminal_size()
        return size.lines, size.columns
    else:
        import termios, fcntl, struct
        call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8)
        height, width = struct.unpack("hhhh", call)[:2]
        return height, width 
Example 19
Project: CrystaLattE   Author: carlosborca   File: psithonyzer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def psz_print_results(results, crystal_lattice_energy, verbose=0):
    """Prints a summary of the energy results at the end of the
    execution.
    
    Arguments:
    <int> verbose
        Adjusts the level of detail of the printouts.
    """
    try:
        term_size = shutil.get_terminal_size().columns
    except AttributeError:
        term_size = 0

    if verbose >= 1:
        print("Summary of results:")
        print("---------------------------+--------------+------+--------------+---------------+--------------+----------------{}".format("-"*(term_size - 112)))
        print("                           | Non-Additive | Num. |        N-mer | Partial Crys. |  Calculation | Minimum Monomer")
        print("N-mer Name                 |    MB Energy | Rep. | Contribution | Lattice Ener. |     Priority | Separations")
        print("                           |     (kJ/mol) |  (#) |     (kJ/mol) |      (kJ/mol) | (Arb. Units) | (A)")
        print("---------------------------+--------------+------+--------------+---------------+--------------+----------------{}".format("-"*(term_size - 112)))
        for result in results:
            print(result)
        print("---------------------------+--------------+------+--------------+---------------+--------------+----------------{}\n".format("-"*(term_size - 112)))
        #print("Crystal Lattice Energy (Eh)       = {:5.8f}".format(crystal_lattice_energy / 2625.500)) # Same value as in psi_hartree2kJmol
        print("Crystal Lattice Energy (kJ/mol)   = {:9.8f}".format(crystal_lattice_energy))
        print("Crystal Lattice Energy (kcal/mol) = {:9.8f}\n".format(crystal_lattice_energy / 4.184)) # Same value as in psi_cal2J
# ======================================================================


# ====================================================================== 
Example 20
Project: CrystaLattE   Author: carlosborca   File: crystalatte.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def extract_element(label):
    """Converts an "_atom_type_label" into an element name.
    """

    elem2 = ['He','Li','Be','Ne','Na','Mg','Al','Si','Cl','Ar','Ca','Sc','Ti',
             'Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr',
             'Rb','Sr','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn',
             'Sb','Te','Xe','Cs','Ba','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd',
             'Tb','Dy','Ho','Er','Tm','Yb','Lu','Hf','Ta','Re','Os','Ir','Pt',
             'Au','Hg','Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th','Pa',
             'Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr']

    if (label[0:2] in elem2):
        return label[0:2]

    elem1 = ['H','B','C','N','O','F','P','S','K','V','Y','I','W','U']

    if (label[0] in elem1):
        return label[0]

    print("{}".format("~"*(shutil.get_terminal_size().columns)))
    print('WARNING: could not convert "%s" into element name!' % label)
    print("{}".format("~"*(shutil.get_terminal_size().columns)))
    return label
# ======================================================================


# ====================================================================== 
Example 21
Project: CrystaLattE   Author: carlosborca   File: crystalatte.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def print_results(results, crystal_lattice_energy, verbose=0):
    """Prints a summary of the energy results at the end of the
    execution.
    
    Arguments:
    <int> verbose
        Adjusts the level of detail of the printouts.
    """

    if verbose >= 1:
        print("Summary of results:")
        print("---------------------------+--------------+------+--------------+---------------+--------------+----------------{}".format("-"*(shutil.get_terminal_size().columns - 112)))
        print("                           | Non-Additive | Num. |        N-mer | Partial Crys. |  Calculation | Minimum Monomer")
        print("N-mer Name                 |    MB Energy | Rep. | Contribution | Lattice Ener. |     Priority | Separations")
        print("                           |     (kJ/mol) |  (#) |     (kJ/mol) |      (kJ/mol) | (Arb. Units) | (A)")
        print("---------------------------+--------------+------+--------------+---------------+--------------+----------------{}".format("-"*(shutil.get_terminal_size().columns - 112)))
        for result in results:
            print(result)
        print("---------------------------+--------------+------+--------------+---------------+--------------+----------------{}\n".format("-"*(shutil.get_terminal_size().columns - 112)))
        #print("Crystal Lattice Energy (Eh)       = {:5.8f}".format(crystal_lattice_energy))
        print("Crystal Lattice Energy (kJ/mol)   = {:9.8f}".format(crystal_lattice_energy * qcel.constants.hartree2kcalmol * qcel.constants.cal2J))
        print("Crystal Lattice Energy (kcal/mol) = {:9.8f}\n".format(crystal_lattice_energy * qcel.constants.hartree2kcalmol))
# ======================================================================


# ====================================================================== 
Example 22
Project: NiujiaoDebugger   Author: MrSrc   File: test_shutil.py    GNU General Public License v3.0 5 votes vote down vote up
def test_does_not_crash(self):
        """Check if get_terminal_size() returns a meaningful value.

        There's no easy portable way to actually check the size of the
        terminal, so let's check if it returns something sensible instead.
        """
        size = shutil.get_terminal_size()
        self.assertGreaterEqual(size.columns, 0)
        self.assertGreaterEqual(size.lines, 0) 
Example 23
Project: NiujiaoDebugger   Author: MrSrc   File: test_shutil.py    GNU General Public License v3.0 5 votes vote down vote up
def test_os_environ_first(self):
        "Check if environment variables have precedence"

        with support.EnvironmentVarGuard() as env:
            env['COLUMNS'] = '777'
            del env['LINES']
            size = shutil.get_terminal_size()
        self.assertEqual(size.columns, 777)

        with support.EnvironmentVarGuard() as env:
            del env['COLUMNS']
            env['LINES'] = '888'
            size = shutil.get_terminal_size()
        self.assertEqual(size.lines, 888) 
Example 24
Project: NiujiaoDebugger   Author: MrSrc   File: test_shutil.py    GNU General Public License v3.0 5 votes vote down vote up
def test_bad_environ(self):
        with support.EnvironmentVarGuard() as env:
            env['COLUMNS'] = 'xxx'
            env['LINES'] = 'yyy'
            size = shutil.get_terminal_size()
        self.assertGreaterEqual(size.columns, 0)
        self.assertGreaterEqual(size.lines, 0) 
Example 25
Project: Health-Checker   Author: KriAga   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example 26
Project: Health-Checker   Author: KriAga   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except Exception:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except Exception:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 27
Project: Health-Checker   Author: KriAga   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example 28
Project: Health-Checker   Author: KriAga   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 29
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_format.py    MIT License 5 votes vote down vote up
def test_repr_truncates_terminal_size(self, monkeypatch):
        # see gh-21180

        terminal_size = (118, 96)
        monkeypatch.setattr(
            "pandas.io.formats.format.get_terminal_size", lambda: terminal_size
        )

        index = range(5)
        columns = pd.MultiIndex.from_tuples(
            [
                ("This is a long title with > 37 chars.", "cat"),
                ("This is a loooooonger title with > 43 chars.", "dog"),
            ]
        )
        df = pd.DataFrame(1, index=index, columns=columns)

        result = repr(df)

        h1, h2 = result.split("\n")[:2]
        assert "long" in h1
        assert "loooooonger" in h1
        assert "cat" in h2
        assert "dog" in h2

        # regular columns
        df2 = pd.DataFrame({"A" * 41: [1, 2], "B" * 41: [1, 2]})
        result = repr(df2)

        assert df2.columns[0] in result.split("\n")[0] 
Example 30
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_format.py    MIT License 5 votes vote down vote up
def test_repr_truncates_terminal_size_full(self, monkeypatch):
        # GH 22984 ensure entire window is filled
        terminal_size = (80, 24)
        df = pd.DataFrame(np.random.rand(1, 7))

        monkeypatch.setattr(
            "pandas.io.formats.format.get_terminal_size", lambda: terminal_size
        )
        assert "..." not in str(df) 
Example 31
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_format.py    MIT License 5 votes vote down vote up
def test_auto_detect(self):
        term_width, term_height = get_terminal_size()
        fac = 1.05  # Arbitrary large factor to exceed term width
        cols = range(int(term_width * fac))
        index = range(10)
        df = DataFrame(index=index, columns=cols)
        with option_context("mode.sim_interactive", True):
            with option_context("max_rows", None):
                with option_context("max_columns", None):
                    # Wrap around with None
                    assert has_expanded_repr(df)
            with option_context("max_rows", 0):
                with option_context("max_columns", 0):
                    # Truncate with auto detection.
                    assert has_horizontally_truncated_repr(df)

            index = range(int(term_height * fac))
            df = DataFrame(index=index, columns=cols)
            with option_context("max_rows", 0):
                with option_context("max_columns", None):
                    # Wrap around with None
                    assert has_expanded_repr(df)
                    # Truncate vertically
                    assert has_vertically_truncated_repr(df)

            with option_context("max_rows", None):
                with option_context("max_columns", 0):
                    assert has_horizontally_truncated_repr(df) 
Example 32
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: series.py    MIT License 5 votes vote down vote up
def __repr__(self):
        """
        Return a string representation for a particular Series.
        """
        buf = StringIO("")
        width, height = get_terminal_size()
        max_rows = (
            height
            if get_option("display.max_rows") == 0
            else get_option("display.max_rows")
        )
        min_rows = (
            height
            if get_option("display.max_rows") == 0
            else get_option("display.min_rows")
        )
        show_dimensions = get_option("display.show_dimensions")

        self.to_string(
            buf=buf,
            name=self.name,
            dtype=self.dtype,
            min_rows=min_rows,
            max_rows=max_rows,
            length=show_dimensions,
        )
        result = buf.getvalue()

        return result 
Example 33
Project: schemathesis   Author: kiwicom   File: default.py    MIT License 5 votes vote down vote up
def get_terminal_width() -> int:
    return shutil.get_terminal_size().columns 
Example 34
Project: chord-sequence-chooser   Author: bwetherfield   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example 35
Project: chord-sequence-chooser   Author: bwetherfield   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 36
Project: thamos   Author: thoth-station   File: cli.py    GNU General Public License v3.0 5 votes vote down vote up
def _print_header(header: str) -> None:
    """Print header to terminal respecting terminal size."""
    terminal_size = get_terminal_size()
    padding = (terminal_size.columns - len(header) - 2) // 2
    click.echo(padding * " " + header)
    click.echo(padding * " " + "=" * len(header) + "  \n") 
Example 37
Project: ChromaTerm   Author: hSaria   File: __init__.py    MIT License 5 votes vote down vote up
def run_program(config, program_args):
    """Fork a program with its stdout set to use an os.opentty. Once the program
    closes, it will write a dummy byte to the close pipe. config['read_fds'] is
    populated with the program FD followed by the close FD, in that order."""
    import fcntl
    import termios
    import shutil
    import struct

    # Create the tty and close_signal file decriptors
    tty_r, tty_w = os.openpty()
    close_r, close_w = os.pipe()

    config['read_fds'] = [tty_r, close_r]

    # Update terminal size on the program's TTY (starts uninitialized)
    window_size = shutil.get_terminal_size()
    window_size = struct.pack('2H', window_size.lines, window_size.columns)
    fcntl.ioctl(tty_w, termios.TIOCSWINSZ, window_size)

    if os.fork() == 0:  # Program
        try:
            import subprocess
            subprocess.run(program_args, check=False, stdout=tty_w)
        except FileNotFoundError:
            eprint(program_args[0] + ': command not found')
        except KeyboardInterrupt:  # pragma: no cover  # Limitation when forking
            pass  # Program gets the signal; CT shouldn't freak out
        finally:
            os.write(close_w, b'\x00')
        sys.exit() 
Example 38
Project: python-netsurv   Author: sofia-netsurv   File: terminalwriter.py    MIT License 5 votes vote down vote up
def _getdimensions():
    if py33:
        import shutil
        size = shutil.get_terminal_size()
        return size.lines, size.columns
    else:
        import termios, fcntl, struct
        call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8)
        height, width = struct.unpack("hhhh", call)[:2]
        return height, width 
Example 39
Project: python-netsurv   Author: sofia-netsurv   File: terminalwriter.py    MIT License 5 votes vote down vote up
def _getdimensions():
    if py33:
        import shutil
        size = shutil.get_terminal_size()
        return size.lines, size.columns
    else:
        import termios, fcntl, struct
        call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8)
        height, width = struct.unpack("hhhh", call)[:2]
        return height, width 
Example 40
Project: FUTU_Stop_Loss   Author: BigtoC   File: terminal.py    MIT License 5 votes vote down vote up
def get_terminal_size():
    """
    Detect terminal size and return tuple = (width, height).

    Only to be used when running in a terminal. Note that the IPython notebook,
    IPython zmq frontends, or IDLE do not run in a terminal,
    """
    import platform

    if PY3:
        return shutil.get_terminal_size()

    current_os = platform.system()
    tuple_xy = None
    if current_os == 'Windows':
        tuple_xy = _get_terminal_size_windows()
        if tuple_xy is None:
            tuple_xy = _get_terminal_size_tput()
            # needed for window's python in cygwin's xterm!
    if current_os == 'Linux' or \
        current_os == 'Darwin' or \
            current_os.startswith('CYGWIN'):
        tuple_xy = _get_terminal_size_linux()
    if tuple_xy is None:
        tuple_xy = (80, 25)      # default value
    return tuple_xy 
Example 41
Project: gravitation   Author: pleiszenburg   File: benchmark.py    GNU General Public License v2.0 5 votes vote down vote up
def _process_data(kernel, threads, bodies, results_dict, outputlines_list, fh, display):
	"""factory, returning function for reading a worker log in realtime"""
	def callback(stream_id, msg_line):
		fh.write(msg_line + '\n')
		if display == 'log':
			print(msg_line)
		outputlines_list.append(msg_line)
		try:
			msg = json.loads(msg_line)
		except:
			return
		results_kernel_dict = results_dict[kernel][threads]
		if msg['log'] == 'BEST_TIME':
			if bodies not in results_kernel_dict.keys():
				results_kernel_dict[bodies] = msg['value']
			elif results_kernel_dict[bodies] != msg['value']:
				results_kernel_dict[bodies] = msg['value']
			else:
				return
		else:
			return
		if display != 'plot':
			return
		x = sorted(list(results_kernel_dict.keys()))
		y = [results_kernel_dict[n] for n in x]
		t = shutil.get_terminal_size((80, 20))
		fig = apl.figure()
		fig.plot(
			x, y,
			label = '{kernel}@{threads}'.format(kernel = kernel, threads = threads),
			width = t.columns, height = t.lines,
			extra_gnuplot_arguments = [
				'set logscale x 2',
				'set format y "10^{%L}"',
				'set logscale y 10',
				]
			)
		fig.show()
	return callback 
Example 42
Project: mechkbot   Author: cjgibson   File: bot.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        super(self.__class__, self).__init__()
        self.prompt = __CMD_STR__
        self.size = shutil.get_terminal_size()
        self.height, self.width = self.size.lines, self.size.columns 
Example 43
Project: azure-cli-extensions   Author: Azure   File: util.py    MIT License 5 votes vote down vote up
def _size_36():
    """ returns the rows, columns of terminal """
    from shutil import get_terminal_size
    dim = get_terminal_size()
    if isinstance(dim, list):
        return dim[0], dim[1]
    return dim.lines, dim.columns 
Example 44
Project: python-key-chatbot   Author: tavik000   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example 45
Project: python-key-chatbot   Author: tavik000   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 46
Project: MARRtino-2.0   Author: DaniAffCH   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size())  # type: ignore 
Example 47
Project: MARRtino-2.0   Author: DaniAffCH   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except Exception:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except Exception:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 48
Project: unhuman-resources   Author: agajdosi   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size())  # type: ignore 
Example 49
Project: unhuman-resources   Author: agajdosi   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except Exception:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except Exception:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 50
Project: unhuman-resources   Author: agajdosi   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size())  # type: ignore