aboutsummaryrefslogtreecommitdiffstats
path: root/termcast_client/py2compat.py
diff options
context:
space:
mode:
authorThomas Ballinger <thomasballinger@gmail.com>2014-10-16 21:36:20 -0400
committerThomas Ballinger <thomasballinger@gmail.com>2014-10-16 21:37:55 -0400
commit31cea814977c32b02bf9166cf4490f70e9861d1c (patch)
treef2ff4e93abde9e7406c9c8a08710d42c0f6380b8 /termcast_client/py2compat.py
parent597219dbcddb3e49090a2b5ae883a1e2935bf836 (diff)
downloadpython-termcast-client-31cea814977c32b02bf9166cf4490f70e9861d1c.tar.gz
python-termcast-client-31cea814977c32b02bf9166cf4490f70e9861d1c.zip
Add Python 2 compatibility
Diffstat (limited to 'termcast_client/py2compat.py')
-rw-r--r--termcast_client/py2compat.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/termcast_client/py2compat.py b/termcast_client/py2compat.py
new file mode 100644
index 0000000..16f2b34
--- /dev/null
+++ b/termcast_client/py2compat.py
@@ -0,0 +1,40 @@
+import fcntl
+import os
+import struct
+import sys
+import termios
+
+from collections import namedtuple
+
+terminal_size = namedtuple('terminal_size', ['columns', 'lines'])
+
+py2 = sys.version_info[0] == 2
+
+def get_terminal_size(fallback=(80, 24)):
+ """Based on Python 3 os.get_terminal_size()"""
+ # columns, lines are the working values
+ try:
+ columns = int(os.environ['COLUMNS'])
+ except (KeyError, ValueError):
+ columns = 0
+
+ try:
+ lines = int(os.environ['LINES'])
+ except (KeyError, ValueError):
+ lines = 0
+
+ # only query if necessary
+ if columns <= 0 or lines <= 0:
+ try:
+ winsize = fcntl.ioctl(sys.__stdout__.fileno(),
+ termios.TIOCGWINSZ, '\000' * 8)
+ size = terminal_size(*struct.unpack('hhhh', winsize)[1::-1])
+
+ except (NameError, OSError):
+ size = terminal_size(*fallback)
+ if columns <= 0:
+ columns = size.columns
+ if lines <= 0:
+ lines = size.lines
+
+ return terminal_size(*size)