diff --git Lib/argparse.py Lib/argparse.py index f0cfe27..71c3a4c 100644 --- Lib/argparse.py +++ Lib/argparse.py @@ -89,6 +89,9 @@ import os as _os import re as _re import sys as _sys import textwrap as _textwrap +import fcntl as _fcntl +import termios as _termios +import struct as _struct from gettext import gettext as _, ngettext @@ -140,11 +143,24 @@ def _ensure_value(namespace, name, value): setattr(namespace, name, value) return getattr(namespace, name) - # =============== # Formatting Help # =============== +def _terminal_width(default=80): + try: + # An environment variable has higher priority + width = int(_os.environ['COLUMNS']) + except (KeyError, ValueError): + format = _struct.pack('HHHH', 0, 0, 0, 0) + try: + output = _fcntl.ioctl(1, _termios.TIOCGWINSZ, format) + width = _struct.unpack('HHHH', output)[1] + except IOError: + # If nothing worked, let's follow the time-honored tradition + width = default + return width + class HelpFormatter(object): """Formatter for generating usage messages and argument help strings. @@ -160,11 +176,7 @@ class HelpFormatter(object): # default setting for width if width is None: - try: - width = int(_os.environ['COLUMNS']) - except (KeyError, ValueError): - width = 80 - width -= 2 + width = _terminal_width() - 2 self._prog = prog self._indent_increment = indent_increment