Created
November 2, 2012 11:09
-
-
Save anonymous/4000231 to your computer and use it in GitHub Desktop.
termsize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from ctypes import c_ushort, sizeof, Structure | |
import fcntl | |
import sys | |
import termios | |
class WinSize(Structure): | |
'''To get the terminal size information via the UNIX systemcall | |
'ioctl()'. This is needed cause the control sequence '\033[18t' | |
only work proper in xterm-like terminals but not without running | |
X-Server. | |
The 'WinSize.from_file()'-method returns the result of 'ioctl()' | |
and is wrapped by 'window_size()'. Use this function instead. | |
Thanks to 'BlackJack' from 'python-forum.de' for this | |
peace of code...! | |
''' | |
_fields_ = [ | |
('rows', c_ushort), | |
('columns', c_ushort), | |
('x_pixels', c_ushort), # Unused. | |
('y_pixels', c_ushort), # Unused. | |
] | |
@classmethod | |
def from_file(cls, tty_file): | |
result = fcntl.ioctl(tty_file, | |
termios.TIOCGWINSZ, '\0' * sizeof(cls)) | |
return cls.from_buffer_copy(result) | |
def term_size(): | |
'''term_size() -> (rows, columns) | |
In contrast to graphical frameworks which not working with | |
chars but with pixels as unit the result of this function | |
begins with (1, 1) that means the upper left corner.''' | |
size = WinSize.from_file(sys.stdout) | |
return size.rows, size.columns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment