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
6#
8import os
9import struct
10import platform
11import subprocess
14def get_terminal_size():
15 '''
16 Get terminal size.
18 Works on linux,os x,windows,cygwin(windows)
20 originally retrieved from:
21 http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
22 '''
24 current_os = platform.system()
25 tuple_xy = None
26 if current_os == 'Windows':
27 tuple_xy = _get_terminal_size_windows()
28 if tuple_xy is None:
29 tuple_xy = _get_terminal_size_tput()
30 # needed for window's python in cygwin's xterm!
32 if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'):
33 tuple_xy = _get_terminal_size_linux()
35 if tuple_xy is None:
36 tuple_xy = (80, 25) # default value
38 return tuple_xy
41def _get_terminal_size_windows():
42 try:
43 from ctypes import windll, create_string_buffer
44 # stdin handle is -10
45 # stdout handle is -11
46 # stderr handle is -12
47 h = windll.kernel32.GetStdHandle(-12)
48 csbi = create_string_buffer(22)
49 res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
50 if res:
51 (bufx, bufy, curx, cury, wattr,
52 left, top, right, bottom,
53 maxx, maxy) = struct.unpack('hhhhHhhhhhh', csbi.raw)
54 sizex = right - left + 1
55 sizey = bottom - top + 1
56 return sizex, sizey
57 except Exception:
58 pass
61def _get_terminal_size_tput():
62 # get terminal width
63 # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window # noqa
64 try:
65 cols = int(subprocess.check_call(['tput' 'cols']))
66 rows = int(subprocess.check_call(['tput', 'lines']))
67 return (cols, rows)
68 except Exception:
69 pass
72def _get_terminal_size_linux():
74 def ioctl_GWINSZ(fd):
75 try:
76 import fcntl
77 import termios
78 cr = struct.unpack(
79 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
80 return cr
81 except Exception:
82 pass
84 cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
86 if not cr:
87 try:
88 fd = os.open(os.ctermid(), os.O_RDONLY)
89 cr = ioctl_GWINSZ(fd)
90 os.close(fd)
91 except Exception:
92 pass
94 if not cr:
95 try:
96 cr = (os.environ['LINES'], os.environ['COLUMNS'])
97 except Exception:
98 return None
100 return int(cr[1]), int(cr[0])
103if __name__ == '__main__':
104 sizex, sizey = get_terminal_size()
105 print(sizex, sizey)