summaryrefslogtreecommitdiff
path: root/ttystatus/messager.py
diff options
context:
space:
mode:
authorLars Wirzenius <liw@liw.fi>2010-06-05 15:13:00 +1200
committerLars Wirzenius <liw@liw.fi>2010-06-05 15:13:00 +1200
commite5b68edac27144386a6d7d0b0f4c00994f8b4d1e (patch)
tree753491c563b31077a0dc73c0807d630fa8f98661 /ttystatus/messager.py
parentfefc681a32962524db4e3b63793762dd67bee42b (diff)
downloadpython-ttystatus-e5b68edac27144386a6d7d0b0f4c00994f8b4d1e.tar.gz
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.
Diffstat (limited to 'ttystatus/messager.py')
-rw-r--r--ttystatus/messager.py25
1 files changed, 24 insertions, 1 deletions
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 <http://www.gnu.org/licenses/>.
+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():