Coverage for /usr/local/lib/python3.11/dist-packages/pyrocko/get_terminal_size.py: 58%
60 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-10-06 15:01 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2023-10-06 15:01 +0000
1#
2# This file is NOT part of Pyrocko.
3#
4# Code is considered public domain, based on
5# https://gist.github.com/jtriley/1108174
7'''
8Cross platform get terminal size utilities.
9'''
11import os
12import struct
13import platform
14import subprocess
17def get_terminal_size():
18 '''
19 Get terminal size.
21 Works on linux,os x,windows,cygwin(windows)
23 originally retrieved from:
24 http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
25 '''
27 current_os = platform.system()
28 tuple_xy = None
29 if current_os == 'Windows':
30 tuple_xy = _get_terminal_size_windows()
31 if tuple_xy is None:
32 tuple_xy = _get_terminal_size_tput()
33 # needed for window's python in cygwin's xterm!
35 if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'):
36 tuple_xy = _get_terminal_size_linux()
38 if tuple_xy is None:
39 tuple_xy = (80, 25) # default value
41 return tuple_xy
44def _get_terminal_size_windows():
45 try:
46 from ctypes import windll, create_string_buffer
47 # stdin handle is -10
48 # stdout handle is -11
49 # stderr handle is -12
50 h = windll.kernel32.GetStdHandle(-12)
51 csbi = create_string_buffer(22)
52 res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
53 if res:
54 (bufx, bufy, curx, cury, wattr,
55 left, top, right, bottom,
56 maxx, maxy) = struct.unpack('hhhhHhhhhhh', csbi.raw)
57 sizex = right - left + 1
58 sizey = bottom - top + 1
59 return sizex, sizey
60 except Exception:
61 pass
64def _get_terminal_size_tput():
65 # get terminal width
66 # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window # noqa
67 try:
68 cols = int(subprocess.check_call(['tput' 'cols']))
69 rows = int(subprocess.check_call(['tput', 'lines']))
70 return (cols, rows)
71 except Exception:
72 pass
75def _get_terminal_size_linux():
77 def ioctl_GWINSZ(fd):
78 try:
79 import fcntl
80 import termios
81 cr = struct.unpack(
82 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
83 return cr
84 except Exception:
85 pass
87 cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
89 if not cr:
90 try:
91 fd = os.open(os.ctermid(), os.O_RDONLY)
92 cr = ioctl_GWINSZ(fd)
93 os.close(fd)
94 except Exception:
95 pass
97 if not cr:
98 try:
99 cr = (os.environ['LINES'], os.environ['COLUMNS'])
100 except Exception:
101 return None
103 return int(cr[1]), int(cr[0])
106if __name__ == '__main__':
107 sizex, sizey = get_terminal_size()
108 print(sizex, sizey)