From e5b68edac27144386a6d7d0b0f4c00994f8b4d1e Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Sat, 5 Jun 2010 15:13:00 +1200 Subject: Query terminal for its width at startup. Allow output go to StringIO, which does not have fileno. Good for test suite, and good for user, perhaps, for deranged values of user. --- ttystatus/messager.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) (limited to 'ttystatus/messager.py') diff --git a/ttystatus/messager.py b/ttystatus/messager.py index 6433391..c6b4f6e 100644 --- a/ttystatus/messager.py +++ b/ttystatus/messager.py @@ -14,6 +14,8 @@ # along with this program. If not, see . +import fcntl +import struct import sys import time @@ -28,13 +30,34 @@ class Messager(object): self._last_time = 0 # When did we write last? self._period = 1 # How long between updates? self._cached_msg = '' # Last message from user, to write() method. - self.width = 80 # Width of terminal + self.width = self._get_terminal_width() # Width of terminal def _now(self): '''Return current time.''' # This is a wrapper around time.time(), for testing. return time.time() + def _get_terminal_width(self): # pragma: no cover + '''Return width of terminal in characters. + + If this fails, assume 80. + + Borrowed and adapted from bzrlib. + + ''' + + default_width = 80 + try: + s = struct.pack('HHHH', 0, 0, 0, 0) + x = fcntl.ioctl(self.output.fileno(), termios.TIOCGWINSZ, s) + return struct.unpack('HHHH', x)[1] + except IOError: + return default_width + except AttributeError: + if not hasattr(self.output, 'fileno'): + return default_width + raise + def _raw_write(self, string): '''Write raw data if output is terminal.''' if self.output.isatty(): -- cgit v1.2.1