##// END OF EJS Templates
Vendor shutil.get_terminal_size....
Matthias Bussonnier -
Show More
@@ -0,0 +1,103 b''
1 # vendored version of backports.get_terminal_size as nemesapece package are a
2 # mess and break, especially on ubuntu. This file is under MIT Licence.
3 # See https://pypi.python.org/pypi/backports.shutil_get_terminal_size
4 """This is a backport of shutil.get_terminal_size from Python 3.3.
5
6 The original implementation is in C, but here we use the ctypes and
7 fcntl modules to create a pure Python version of os.get_terminal_size.
8 """
9
10 import os
11 import struct
12 import sys
13
14 from collections import namedtuple
15
16 __all__ = ["get_terminal_size"]
17
18
19 terminal_size = namedtuple("terminal_size", "columns lines")
20
21 try:
22 from ctypes import windll, create_string_buffer
23
24 _handles = {
25 0: windll.kernel32.GetStdHandle(-10),
26 1: windll.kernel32.GetStdHandle(-11),
27 2: windll.kernel32.GetStdHandle(-12),
28 }
29
30 def _get_terminal_size(fd):
31 columns = lines = 0
32
33 try:
34 handle = _handles[fd]
35 csbi = create_string_buffer(22)
36 res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
37 if res:
38 res = struct.unpack("hhhhHhhhhhh", csbi.raw)
39 left, top, right, bottom = res[5:9]
40 columns = right - left + 1
41 lines = bottom - top + 1
42 except Exception:
43 pass
44
45 return terminal_size(columns, lines)
46
47 except ImportError:
48 import fcntl
49 import termios
50
51 def _get_terminal_size(fd):
52 try:
53 res = fcntl.ioctl(fd, termios.TIOCGWINSZ, b"\x00" * 4)
54 lines, columns = struct.unpack("hh", res)
55 except Exception:
56 columns = lines = 0
57
58 return terminal_size(columns, lines)
59
60
61 def get_terminal_size(fallback=(80, 24)):
62 """Get the size of the terminal window.
63
64 For each of the two dimensions, the environment variable, COLUMNS
65 and LINES respectively, is checked. If the variable is defined and
66 the value is a positive integer, it is used.
67
68 When COLUMNS or LINES is not defined, which is the common case,
69 the terminal connected to sys.__stdout__ is queried
70 by invoking os.get_terminal_size.
71
72 If the terminal size cannot be successfully queried, either because
73 the system doesn't support querying, or because we are not
74 connected to a terminal, the value given in fallback parameter
75 is used. Fallback defaults to (80, 24) which is the default
76 size used by many terminal emulators.
77
78 The value returned is a named tuple of type os.terminal_size.
79 """
80 # Try the environment first
81 try:
82 columns = int(os.environ["COLUMNS"])
83 except (KeyError, ValueError):
84 columns = 0
85
86 try:
87 lines = int(os.environ["LINES"])
88 except (KeyError, ValueError):
89 lines = 0
90
91 # Only query if necessary
92 if columns <= 0 or lines <= 0:
93 try:
94 size = _get_terminal_size(sys.__stdout__.fileno())
95 except (NameError, OSError):
96 size = terminal_size(*fallback)
97
98 if columns <= 0:
99 columns = size.columns
100 if lines <= 0:
101 lines = size.lines
102
103 return terminal_size(columns, lines)
@@ -1,120 +1,125 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with terminals.
3 Utilities for working with terminals.
4
4
5 Authors:
5 Authors:
6
6
7 * Brian E. Granger
7 * Brian E. Granger
8 * Fernando Perez
8 * Fernando Perez
9 * Alexander Belchenko (e-mail: bialix AT ukr.net)
9 * Alexander Belchenko (e-mail: bialix AT ukr.net)
10 """
10 """
11
11
12 from __future__ import absolute_import
13
12 # Copyright (c) IPython Development Team.
14 # Copyright (c) IPython Development Team.
13 # Distributed under the terms of the Modified BSD License.
15 # Distributed under the terms of the Modified BSD License.
14
16
15 import os
17 import os
16 import sys
18 import sys
17 import warnings
19 import warnings
18 try:
20 try:
19 from shutil import get_terminal_size as _get_terminal_size
21 from shutil import get_terminal_size as _get_terminal_size
20 except ImportError:
22 except ImportError:
21 # use backport on Python 2
23 # use backport on Python 2
24 try:
22 from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
25 from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
26 except ImportError:
27 from ._get_terminal_size import _get_terminal_size
23
28
24 from . import py3compat
29 from . import py3compat
25
30
26 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
27 # Code
32 # Code
28 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
29
34
30 # This variable is part of the expected API of the module:
35 # This variable is part of the expected API of the module:
31 ignore_termtitle = True
36 ignore_termtitle = True
32
37
33
38
34
39
35 if os.name == 'posix':
40 if os.name == 'posix':
36 def _term_clear():
41 def _term_clear():
37 os.system('clear')
42 os.system('clear')
38 elif sys.platform == 'win32':
43 elif sys.platform == 'win32':
39 def _term_clear():
44 def _term_clear():
40 os.system('cls')
45 os.system('cls')
41 else:
46 else:
42 def _term_clear():
47 def _term_clear():
43 pass
48 pass
44
49
45
50
46
51
47 def toggle_set_term_title(val):
52 def toggle_set_term_title(val):
48 """Control whether set_term_title is active or not.
53 """Control whether set_term_title is active or not.
49
54
50 set_term_title() allows writing to the console titlebar. In embedded
55 set_term_title() allows writing to the console titlebar. In embedded
51 widgets this can cause problems, so this call can be used to toggle it on
56 widgets this can cause problems, so this call can be used to toggle it on
52 or off as needed.
57 or off as needed.
53
58
54 The default state of the module is for the function to be disabled.
59 The default state of the module is for the function to be disabled.
55
60
56 Parameters
61 Parameters
57 ----------
62 ----------
58 val : bool
63 val : bool
59 If True, set_term_title() actually writes to the terminal (using the
64 If True, set_term_title() actually writes to the terminal (using the
60 appropriate platform-specific module). If False, it is a no-op.
65 appropriate platform-specific module). If False, it is a no-op.
61 """
66 """
62 global ignore_termtitle
67 global ignore_termtitle
63 ignore_termtitle = not(val)
68 ignore_termtitle = not(val)
64
69
65
70
66 def _set_term_title(*args,**kw):
71 def _set_term_title(*args,**kw):
67 """Dummy no-op."""
72 """Dummy no-op."""
68 pass
73 pass
69
74
70
75
71 def _set_term_title_xterm(title):
76 def _set_term_title_xterm(title):
72 """ Change virtual terminal title in xterm-workalikes """
77 """ Change virtual terminal title in xterm-workalikes """
73 sys.stdout.write('\033]0;%s\007' % title)
78 sys.stdout.write('\033]0;%s\007' % title)
74
79
75 if os.name == 'posix':
80 if os.name == 'posix':
76 TERM = os.environ.get('TERM','')
81 TERM = os.environ.get('TERM','')
77 if TERM.startswith('xterm'):
82 if TERM.startswith('xterm'):
78 _set_term_title = _set_term_title_xterm
83 _set_term_title = _set_term_title_xterm
79 elif sys.platform == 'win32':
84 elif sys.platform == 'win32':
80 try:
85 try:
81 import ctypes
86 import ctypes
82
87
83 SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
88 SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
84 SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
89 SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
85
90
86 def _set_term_title(title):
91 def _set_term_title(title):
87 """Set terminal title using ctypes to access the Win32 APIs."""
92 """Set terminal title using ctypes to access the Win32 APIs."""
88 SetConsoleTitleW(title)
93 SetConsoleTitleW(title)
89 except ImportError:
94 except ImportError:
90 def _set_term_title(title):
95 def _set_term_title(title):
91 """Set terminal title using the 'title' command."""
96 """Set terminal title using the 'title' command."""
92 global ignore_termtitle
97 global ignore_termtitle
93
98
94 try:
99 try:
95 # Cannot be on network share when issuing system commands
100 # Cannot be on network share when issuing system commands
96 curr = py3compat.getcwd()
101 curr = py3compat.getcwd()
97 os.chdir("C:")
102 os.chdir("C:")
98 ret = os.system("title " + title)
103 ret = os.system("title " + title)
99 finally:
104 finally:
100 os.chdir(curr)
105 os.chdir(curr)
101 if ret:
106 if ret:
102 # non-zero return code signals error, don't try again
107 # non-zero return code signals error, don't try again
103 ignore_termtitle = True
108 ignore_termtitle = True
104
109
105
110
106 def set_term_title(title):
111 def set_term_title(title):
107 """Set terminal title using the necessary platform-dependent calls."""
112 """Set terminal title using the necessary platform-dependent calls."""
108 if ignore_termtitle:
113 if ignore_termtitle:
109 return
114 return
110 _set_term_title(title)
115 _set_term_title(title)
111
116
112
117
113 def freeze_term_title():
118 def freeze_term_title():
114 warnings.warn("This function is deprecated, use toggle_set_term_title()")
119 warnings.warn("This function is deprecated, use toggle_set_term_title()")
115 global ignore_termtitle
120 global ignore_termtitle
116 ignore_termtitle = True
121 ignore_termtitle = True
117
122
118
123
119 def get_terminal_size(defaultx=80, defaulty=25):
124 def get_terminal_size(defaultx=80, defaulty=25):
120 return _get_terminal_size((defaultx, defaulty))
125 return _get_terminal_size((defaultx, defaulty))
General Comments 0
You need to be logged in to leave comments. Login now