1from __future__ import absolute_import, print_function 

2 

3# 

4# This file is NOT part of Pyrocko. 

5# 

6# Code is considered public domain, based on 

7# https://gist.github.com/jtriley/1108174 

8# 

9 

10import os 

11import struct 

12import platform 

13import subprocess 

14 

15 

16def get_terminal_size(): 

17 ''' 

18 Get terminal size. 

19 

20 Works on linux,os x,windows,cygwin(windows) 

21 

22 originally retrieved from: 

23 http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python 

24 ''' 

25 

26 current_os = platform.system() 

27 tuple_xy = None 

28 if current_os == 'Windows': 

29 tuple_xy = _get_terminal_size_windows() 

30 if tuple_xy is None: 

31 tuple_xy = _get_terminal_size_tput() 

32 # needed for window's python in cygwin's xterm! 

33 

34 if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'): 

35 tuple_xy = _get_terminal_size_linux() 

36 

37 if tuple_xy is None: 

38 tuple_xy = (80, 25) # default value 

39 

40 return tuple_xy 

41 

42 

43def _get_terminal_size_windows(): 

44 try: 

45 from ctypes import windll, create_string_buffer 

46 # stdin handle is -10 

47 # stdout handle is -11 

48 # stderr handle is -12 

49 h = windll.kernel32.GetStdHandle(-12) 

50 csbi = create_string_buffer(22) 

51 res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) 

52 if res: 

53 (bufx, bufy, curx, cury, wattr, 

54 left, top, right, bottom, 

55 maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) 

56 sizex = right - left + 1 

57 sizey = bottom - top + 1 

58 return sizex, sizey 

59 except Exception: 

60 pass 

61 

62 

63def _get_terminal_size_tput(): 

64 # get terminal width 

65 # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window # noqa 

66 try: 

67 cols = int(subprocess.check_call(['tput' 'cols'])) 

68 rows = int(subprocess.check_call(['tput', 'lines'])) 

69 return (cols, rows) 

70 except Exception: 

71 pass 

72 

73 

74def _get_terminal_size_linux(): 

75 

76 def ioctl_GWINSZ(fd): 

77 try: 

78 import fcntl 

79 import termios 

80 cr = struct.unpack( 

81 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) 

82 return cr 

83 except Exception: 

84 pass 

85 

86 cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) 

87 

88 if not cr: 

89 try: 

90 fd = os.open(os.ctermid(), os.O_RDONLY) 

91 cr = ioctl_GWINSZ(fd) 

92 os.close(fd) 

93 except Exception: 

94 pass 

95 

96 if not cr: 

97 try: 

98 cr = (os.environ['LINES'], os.environ['COLUMNS']) 

99 except Exception: 

100 return None 

101 

102 return int(cr[1]), int(cr[0]) 

103 

104 

105if __name__ == "__main__": 

106 sizex, sizey = get_terminal_size() 

107 print(sizex, sizey)