我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用os.get_terminal_size()。
def __format_text(text): try: maxcol = os.get_terminal_size().columns # piped output to file or other process except OSError: maxcol = sys.maxsize ret = "" for line in text.splitlines(): ios = io.StringIO() writer = formatter.DumbWriter(ios, maxcol=maxcol) writer.send_flowing_data(line) ret = "{0}{1}\n".format(ret, ios.getvalue()) ios.close() return ret
def __init__(self, unit=2, max_len=100): if max_len > 100: raise IllegalUnitException("The maximum of max_len is 100. %s is too big." % max_len) if unit < 1: raise IllegalUnitException("The minimum of unit is 1. %s is too small." % unit) self._unit = floor(unit) self._max_len = floor(max_len) self._symbol = "#" self._status = 0 self._bar = sys.stdout try: self._column = os.get_terminal_size().columns except (OSError, AttributeError): self._column = 60 self._return = "\r" self._name = "Task"
def test_does_not_crash(self): """Check if get_terminal_size() returns a meaningful value. There's no easy portable way to actually check the size of the terminal, so let's check if it returns something sensible instead. """ try: size = os.get_terminal_size() except OSError as e: if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): # Under win32 a generic OSError can be thrown if the # handle cannot be retrieved self.skipTest("failed to query terminal size") raise self.assertGreaterEqual(size.columns, 0) self.assertGreaterEqual(size.lines, 0)
def test_stty_match(self): """Check if stty returns the same results stty actually tests stdin, so get_terminal_size is invoked on stdin explicitly. If stty succeeded, then get_terminal_size() should work too. """ try: size = subprocess.check_output(['stty', 'size']).decode().split() except (FileNotFoundError, subprocess.CalledProcessError): self.skipTest("stty invocation failed") expected = (int(size[1]), int(size[0])) # reversed order try: actual = os.get_terminal_size(sys.__stdin__.fileno()) except OSError as e: if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): # Under win32 a generic OSError can be thrown if the # handle cannot be retrieved self.skipTest("failed to query terminal size") raise self.assertEqual(expected, actual)
def term_width(): """ Try and get the terminal width """ # Python 3.3 and newer if getattr(os, 'get_terminal_size', None) is not None: try: return os.get_terminal_size().columns except OSError: pass # No reliable/easy way on Windows in 3.2 and older if sys.platform == 'win32': return 80 try: proc = subprocess.Popen(['tput cols'], shell=True, stdout=subprocess.PIPE) out = proc.communicate() if proc.wait() != 0: raise OSError return int(out[0]) except OSError: return 80
def report(): import os cols = os.get_terminal_size().columns print('') print('=' * cols) res = [] for k in sorted(count.values(), reverse=True): res.append([k.funcname, k.count, k.time_total, k.time_average]) return tabulate.tabulate(res, headers=('function', 'count', 'time total', 'time average'))
def __init__(self, cfg_path=""): # Find config file. self.path = self.look_for_config( cfg_path, os.getcwd() + "/sshchan.conf", os.getenv('HOME', default="~") + "/sshchan.conf", "/etc/sshchan.conf") self.root = self.get_cfg_opt("rootdir", "/srv/sshchan", fatal=True) self.boardlist_path = self.get_cfg_opt( "boardlist_path", self.root + "/boardlist") self.postnums_path = self.get_cfg_opt( "postnums_path", self.root + "/postnums") self.version = self.get_cfg_opt("version", "0.0") self.motd = self.get_cfg_opt("motd_path", "/etc/motd") self.server_name = self.get_cfg_opt("name", "an sshchan server") self.username = os.getenv("USERNAME", default="anonymous") self.max_boards = 10 # How many boards can be displayed in top bar. self.display_legacy = self.get_cfg_opt("display_legacy", "False") self.prompt = self.get_cfg_opt("prompt", "sshchan") # self.admin = settings["admin"] # self.salt = settings["salt"] # self.passwd = settings["password"] # Max threads on page. self.max_threads = 14 # Terminal size. self.tty_cols = os.get_terminal_size()[0] self.tty_lines = os.get_terminal_size()[1] # Used for laprint() from Display. self.lines_printed = 0
def get_terminal_height(fd=1): """ Returns height of terminal if it is a tty, 999 otherwise :param fd: file descriptor (default: 1=stdout) """ if os.isatty(fd): height = os.get_terminal_size(fd)[1] else: height = 50 return height
def get_terminal_width(fd=1): """ Returns width of terminal if it is a tty, 999 otherwise :param fd: file descriptor (default: 1=stdout) """ if os.isatty(fd): width = os.get_terminal_size(fd)[0] else: width = 50 return width
def list_entries(custom_quantity=None, filter_read=False, filter_starred=None, oldest=False, trim=True): """ Main function for listing wallabag entries. """ conf.load() quantity = None if custom_quantity is None: try: quantity = os.get_terminal_size().lines - 2 # piped output to file or other process except OSError: quantity = sys.maxsize else: quantity = custom_quantity try: request = api.api_list_entries( quantity, filter_read, filter_starred, oldest) if request.has_error(): print("Error: {0} - {1}".format(request.error_text, request.error_description)) exit(-1) response = json.loads(request.response) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) entries = entry.entrylist(response['_embedded']["items"]) print_entries(entries, trim, (not oldest))
def show(entry_id, colors=True, raw=False, html=False): """ Main function for showing an entry. """ conf.load() try: request = api.api_get_entry(entry_id) __handle_request_error(request) entr = entry.Entry(json.loads(request.response)) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) title = entr.title try: delimiter = "".ljust(os.get_terminal_size().columns, '=') # piped output to file or other process except OSError: delimiter = "\n" article = entr.content if not html: article = html2text(article, colors) output = "{0}\n{1}\n{2}".format(title, delimiter, article) if not raw: output = __format_text(output) print(output)
def center(self, message, border, size=os.get_terminal_size().columns): """ Returns a string with message centered between characters of a given border """ return message.center(size, border)
def format_HR(self, border, size=os.get_terminal_size().columns-1): """ Returns a Horizontal Rule of length size """ return border*size
def fill_screen(self, offset): """ Fills remaining lines of screen with Whitespace """ lines = os.get_terminal_size().lines - 1 if offset < lines: print('\n'*(lines-offset))
def get_terminal_col(self): return os.get_terminal_size().columns
def get_terminal_lines(self): return os.get_terminal_size().lines
def get_col(): return os.get_terminal_size().columns
def set_width(TERM_WIDTH): if TERM_WIDTH in (True, None): TERM_WIDTH, _ = os.get_terminal_size() TERM_WIDTH = max(TERM_WIDTH, 120) if TERM_WIDTH: compact = lambda line: _compact(line, TERM_WIDTH-5) else: TERM_WIDTH = 0 compact = lambda line: line globals().update(locals())
def format_in_columns(elements, total_width=None, sep=" ", indent=" ", min_height=10): """ >>> print format_in_columns(map(str,range(100)), 50) 0 10 20 30 40 50 60 70 80 90 1 11 21 31 41 51 61 71 81 91 2 12 22 32 42 52 62 72 82 92 3 13 23 33 43 53 63 73 83 93 4 14 24 34 44 54 64 74 84 94 5 15 25 35 45 55 65 75 85 95 6 16 26 36 46 56 66 76 86 96 7 17 27 37 47 57 67 77 87 97 8 18 28 38 48 58 68 78 88 98 9 19 29 39 49 59 69 79 89 99 """ if not total_width: try: total_width, _ = os.get_terminal_size() except: total_width = 80 widest = min(max(len(k) for k in elements), total_width) columns = max((total_width - len(indent)) // (widest + len(sep)), 1) height = max(min_height, (len(elements) // columns) + 1) # arrange the elements in columns columns = [[elem for (__, elem) in group] for __, group in itertools.groupby(enumerate(elements), lambda p: p[0]//height)] rows = itertools.zip_longest(*columns) col_max = total_width - len(sep) * (len(columns) - 1) column_lens = [min(max(map(len, column)), col_max) for column in columns] return '\n'.join(indent + sep.join([(string or "").ljust(column_lens[column_num]) for column_num, string in enumerate(row)]) for row in rows)
def init_popup(self, msg): width = max([len(line) for line in msg.splitlines()] + [20]) height = msg.count('\n') + 4 cols, rows = os.get_terminal_size() self.get_pop_up_parameters = lambda: dict(left=max(cols // 2 - width // 2, 1), top=max(rows // 2 - height // 2, 1), overlay_width=width, overlay_height=height) return self.open_pop_up()
def get_pop_up_parameters(self): cols, rows = get_terminal_size() return {'left': 0, 'top': -rows // 2 - 5, 'overlay_width': 50, 'overlay_height': 10}
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 (AttributeError, ValueError, OSError): # stdout is None, closed, detached, or not a terminal, or # os.get_terminal_size() is unsupported size = os.terminal_size(fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return os.terminal_size((columns, lines))
def print_entries(entries, trim, reverse_order=False): """ Builds the output and prints all entries. """ maxlength = sys.maxsize if trim: try: maxlength = os.get_terminal_size().columns # piped output to file or other process except OSError: maxlength = sys.maxsize size_entry_id = 0 show_read_column = False show_starred_column = False if len(entries) > 0: size_entry_id = len(str(entries[0].entry_id)) entry_id_last = len(str(entries[len(entries) - 1].entry_id)) if entry_id_last > size_entry_id: size_entry_id = entry_id_last for item in entries: if item.read: show_read_column = True if item.starred: show_starred_column = True if reverse_order: entries = reversed(entries) for item in entries: entry_id = str(item.entry_id).rjust(size_entry_id) read = " " if item.read: if platform.system() == "Windows": read = "r" else: read = "?" starred = " " if item.starred: starred = "*" title = item.title line = entry_id if show_read_column or show_starred_column: line = line + " " if show_read_column: line = line + read if show_starred_column: line = line + starred line = line + " {0}".format(title) print(line[0:maxlength])
def html2text(html, colors=True): soup = BeautifulSoup(html, "html.parser") # Color h1-h3 if colors: h1colors = '\033[93m' h1colore = '\033[0m' else: h1colors = h1colore = "" for h1 in soup.findAll('h1'): h1.string = "\n{0}{1}{2}".format(h1colors, h1.string, h1colore) for h2 in soup.findAll('h2'): h2.string = "\n{0}{1}{2}".format(h1colors, h2.string, h1colore) for h3 in soup.findAll('h3'): h3.string = "\n{0}{1}{2}".format(h1colors, h3.string, h1colore) if colors: # Color bold texts bcolors = '\033[92m' bcolore = '\033[0m' for bold in soup.findAll('b'): bold.string = "{0}{1}{2}".format(bcolors, bold.string, bcolore) for bold in soup.findAll('strong'): bold.string = "{0}{1}{2}".format(bcolors, bold.string, bcolore) # Replace hr with visual lines try: hrstring = "".ljust(os.get_terminal_size().columns, '-') # piped output to file or other process except OSError: hrstring = "-----" for hr in soup.findAll('hr'): replace = soup.new_tag('p') replace.string = hrstring hr.insert_after(replace) hr.unwrap() # Replace images by information-texts for img in soup.findAll('img'): replace = soup.new_tag('p') try: alt = " \"{0}\"".format(img['alt']) except KeyError: alt = "" replace.string = "[IMAGE{0}]\n".format(alt) img.insert_after(replace) img.unwrap() return soup.text
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))