From bcf2b59fb5f18c09a26da3e9b60a37367f2a28ba Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 8 Feb 2012 23:28:36 +0100 Subject: =?UTF-8?q?Issue=20#13609:=20Add=20two=20functions=20to=20query=20?= =?UTF-8?q?the=20terminal=20size:=20os.get=5Fterminal=5Fsize=20(low=20leve?= =?UTF-8?q?l)=20and=20shutil.get=5Fterminal=5Fsize=20(high=20level).=20Pat?= =?UTF-8?q?ch=20by=20Zbigniew=20J=C4=99drzejewski-Szmek.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lib/shutil.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) (limited to 'Lib/shutil.py') diff --git a/Lib/shutil.py b/Lib/shutil.py index db80faf8b0..6664599ecc 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -878,3 +878,46 @@ def chown(path, user=None, group=None): raise LookupError("no such group: {!r}".format(group)) os.chown(path, _user, _group) + +def get_terminal_size(fallback=(80, 24)): + """Get the size of the terminal window. + + For each of the two dimensions, the environment variable, COLUMNS + and LINES respectively, is checked. If the variable is defined and + the value is a positive integer, it is used. + + When COLUMNS or LINES is not defined, which is the common case, + the terminal connected to sys.__stdout__ is queried + by invoking os.get_terminal_size. + + If the terminal size cannot be successfully queried, either because + the system doesn't support querying, or because we are not + connected to a terminal, the value given in fallback parameter + is used. Fallback defaults to (80, 24) which is the default + size used by many terminal emulators. + + The value returned is a named tuple of type os.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: + size = os.get_terminal_size(sys.__stdout__.fileno()) + except (NameError, OSError): + size = os.terminal_size(fallback) + if columns <= 0: + columns = size.columns + if lines <= 0: + lines = size.lines + + return os.terminal_size((columns, lines)) -- cgit v1.2.1