diff options
Diffstat (limited to 'cliff/utils.py')
-rw-r--r-- | cliff/utils.py | 67 |
1 files changed, 8 insertions, 59 deletions
diff --git a/cliff/utils.py b/cliff/utils.py index 50f3ab6..3fa02a6 100644 --- a/cliff/utils.py +++ b/cliff/utils.py @@ -11,10 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import ctypes import os -import struct -import sys # Each edit operation is assigned different cost, such as: # 'w' means swap operation, the cost is 0; @@ -93,63 +90,15 @@ def damerau_levenshtein(s1, s2, cost): return row1[-1] -def terminal_width(stdout): - if hasattr(os, 'get_terminal_size'): - # python 3.3 onwards has built-in support for getting terminal size - try: - return os.get_terminal_size().columns - except OSError: - return None +def terminal_width(): + """Return terminal width in columns - if sys.platform == 'win32': - return _get_terminal_width_windows(stdout) - else: - return _get_terminal_width_ioctl(stdout) - - -def _get_terminal_width_windows(stdout): - STD_INPUT_HANDLE = -10 - STD_OUTPUT_HANDLE = -11 - STD_ERROR_HANDLE = -12 - - std_to_win_handle = { - sys.stdin: STD_INPUT_HANDLE, - sys.stdout: STD_OUTPUT_HANDLE, - sys.stderr: STD_ERROR_HANDLE} - - std_handle = std_to_win_handle.get(stdout) - if not std_handle: - return None - - handle = ctypes.windll.kernel32.GetStdHandle(std_handle) - csbi = ctypes.create_string_buffer(22) - - res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) - if res: - (size_x, size_y, cur_pos_x, cur_pos_y, attr, - left, top, right, bottom, max_size_x, max_size_y) = struct.unpack( - "hhhhHhhhhhh", csbi.raw) - return size_x - - -def _get_terminal_width_ioctl(stdout): - from fcntl import ioctl - import termios + Uses `os.get_terminal_size` function + :returns: terminal width + :rtype: int or None + """ try: - # winsize structure has 4 unsigned short fields - winsize = b'\0' * struct.calcsize('hhhh') - try: - winsize = ioctl(stdout, termios.TIOCGWINSZ, winsize) - except IOError: - return None - except TypeError: - # this is raised in unit tests as stdout is sometimes a StringIO - return None - winsize = struct.unpack('hhhh', winsize) - columns = winsize[1] - if not columns: - return None - return columns - except IOError: + return os.get_terminal_size().columns + except OSError: return None |