Get terminal width (number of characters) if in a window. Notice: this will try several methods in order to support as many terminals and OS as possible.
()
| 3259 | |
| 3260 | |
| 3261 | def get_terminal_width(): |
| 3262 | # type: () -> Optional[int] |
| 3263 | """Get terminal width (number of characters) if in a window. |
| 3264 | |
| 3265 | Notice: this will try several methods in order to |
| 3266 | support as many terminals and OS as possible. |
| 3267 | """ |
| 3268 | sizex = shutil.get_terminal_size(fallback=(0, 0))[0] |
| 3269 | if sizex != 0: |
| 3270 | return sizex |
| 3271 | # Backups |
| 3272 | if WINDOWS: |
| 3273 | from ctypes import windll, create_string_buffer |
| 3274 | # http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/ |
| 3275 | h = windll.kernel32.GetStdHandle(-12) |
| 3276 | csbi = create_string_buffer(22) |
| 3277 | res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) |
| 3278 | if res: |
| 3279 | (bufx, bufy, curx, cury, wattr, |
| 3280 | left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) # noqa: E501 |
| 3281 | sizex = right - left + 1 |
| 3282 | # sizey = bottom - top + 1 |
| 3283 | return sizex |
| 3284 | return sizex |
| 3285 | # We have various methods |
| 3286 | # COLUMNS is set on some terminals |
| 3287 | try: |
| 3288 | sizex = int(os.environ['COLUMNS']) |
| 3289 | except Exception: |
| 3290 | pass |
| 3291 | if sizex: |
| 3292 | return sizex |
| 3293 | # We can query TIOCGWINSZ |
| 3294 | try: |
| 3295 | import fcntl |
| 3296 | import termios |
| 3297 | s = struct.pack('HHHH', 0, 0, 0, 0) |
| 3298 | x = fcntl.ioctl(1, termios.TIOCGWINSZ, s) |
| 3299 | sizex = struct.unpack('HHHH', x)[1] |
| 3300 | except (IOError, ModuleNotFoundError): |
| 3301 | # If everything failed, return default terminal size |
| 3302 | sizex = 79 |
| 3303 | return sizex |
| 3304 | |
| 3305 | |
| 3306 | def pretty_list(rtlst, # type: List[Tuple[Union[str, List[str]], ...]] |
no outgoing calls
no test coverage detected