我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.tigetnum()。
def supported(self): """ A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ # assuming stderr # isatty() returns False when SSHd into Win32 machine if 'CYGWIN' in os.environ: return True if not sys.stderr.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
def __has_colors(stream): """ Is tty output check :param object stream: input stream :return: bool """ if not hasattr(stream, "isatty"): return False # noinspection PyUnresolvedReferences if not stream.isatty(): return False # auto color only on TTYs # noinspection PyBroadException try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except Exception: # guess false in case of error return False
def supported(cls, stream=sys.stdout): """ A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
def enable_pretty_logging(): """Turns on formatted logging output as configured.""" if (options.log_to_stderr or (options.log_to_stderr is None and not options.log_file_prefix)): # Set up color if we are in a tty and curses is installed color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except: pass channel = logging.StreamHandler() channel.setFormatter(_LogFormatter(color=color)) logging.getLogger().addHandler(channel) if options.log_file_prefix: channel = logging.handlers.RotatingFileHandler( filename=options.log_file_prefix, maxBytes=options.log_file_max_size, backupCount=options.log_file_num_backups) channel.setFormatter(_LogFormatter(color=False)) logging.getLogger().addHandler(channel)
def _height_and_width(self): """Return a tuple of (terminal height, terminal width). Start by trying TIOCGWINSZ (Terminal I/O-Control: Get Window Size), falling back to environment variables (LINES, COLUMNS), and returning (None, None) if those are unavailable or invalid. """ # tigetnum('lines') and tigetnum('cols') update only if we call # setupterm() again. for descriptor in self._init_descriptor, sys.__stdout__: try: return struct.unpack( 'hhhh', ioctl(descriptor, TIOCGWINSZ, '\000' * 8))[0:2] except IOError: # when the output stream or init descriptor is not a tty, such # as when when stdout is piped to another program, fe. tee(1), # these ioctls will raise IOError pass try: return int(environ.get('LINES')), int(environ.get('COLUMNS')) except TypeError: return None, None
def number_of_colors(self): """Return the number of colors the terminal supports. Common values are 0, 8, 16, 88, and 256. Though the underlying capability returns -1 when there is no color support, we return 0. This lets you test more Pythonically:: if term.number_of_colors: ... We also return 0 if the terminal won't tell us how many colors it supports, which I think is rare. """ # This is actually the only remotely useful numeric capability. We # don't name it after the underlying capability, because we deviate # slightly from its behavior, and we might someday wish to give direct # access to it. colors = tigetnum('colors') # Returns -1 if no color support, -2 if no # such cap. # self.__dict__['colors'] = ret # Cache it. It's not changing. # (Doesn't work.) return colors if colors >= 0 else 0
def supported(cls, stream=sys.stdout): """A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except Exception: # guess false in case of error return False
def supported(cls, stream=sys.stdout): """is platform supported A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except Exception: # guess false in case of error return False
def enable_pretty_logging(logger, level='info', queue=None): """Turns on formatted logging output as configured. """ logger.setLevel(getattr(logging, level.upper())) if not logger.handlers: # Set up color if we are in a tty and curses is installed color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except: pass channel = logging.StreamHandler() channel.setFormatter(_LogFormatter(color=color)) logger.addHandler(channel) if queue: queue_handler = QueueHandler(queue) queue_handler.setFormatter(_LogFormatter(color=color)) logger.addHandler(queue_handler)
def number_of_colors(self): """ Read-only property: number of colors supported by terminal. Common values are 0, 8, 16, 88, and 256. Most commonly, this may be used to test whether the terminal supports colors. Though the underlying capability returns -1 when there is no color support, we return 0. This lets you test more Pythonically:: if term.number_of_colors: ... """ # This is actually the only remotely useful numeric capability. We # don't name it after the underlying capability, because we deviate # slightly from its behavior, and we might someday wish to give direct # access to it. # trim value to 0, as tigetnum('colors') returns -1 if no support, # and -2 if no such capability. return max(0, self.does_styling and curses.tigetnum('colors') or -1)
def enable_pretty_logging(logger, level='info'): """Turns on formatted logging output as configured. """ logger.setLevel(getattr(logging, level.upper())) if not logger.handlers: # Set up color if we are in a tty and curses is installed color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except: pass channel = logging.StreamHandler() channel.setFormatter(_LogFormatter(color=color)) logger.addHandler(channel)
def __has_colors(stream, allow_piping=False): """Check if Console Has Color.""" if not hasattr(stream, "isatty"): return False if not stream.isatty(): # not being piped or redirected return allow_piping # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False # Has Color Init
def supported(cls, stream=sys.stdout): """ A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except Exception: # guess false in case of error return False
def supported(cls, stream=sys.stdout): """Check the current platform supports coloring terminal output A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except Exception: # guess false in case of error return False
def __init__(self, term_stream=sys.stdout): """ Create a `TerminalController` and initialize its attributes with appropriate values for the current terminal. `term_stream` is the stream that will be used for terminal output; if this stream is not a tty, then the terminal is assumed to be a dumb terminal (i.e., have no capabilities). """ # Curses isn't available on all platforms try: import curses except: return # If the stream isn't a tty, then assume it has no capabilities. if not term_stream.isatty(): return # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm() except: return # Look up numeric capabilities. self.COLS = curses.tigetnum('cols') self.LINES = curses.tigetnum('lines') # Look up string capabilities. for capability in self._STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(self, attrib, self._tigetstr(cap_name) or '') # Colors set_fg = self._tigetstr('setf') if set_fg: for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, curses.tparm(set_fg, i) or '') set_bg = self._tigetstr('setb') if set_bg: for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, 'BG_'+color, curses.tparm(set_bg, i) or '')
def has_colours(stream): if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: return False
def _stderr_supports_color(): color = False if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except Exception: pass return color
def terminal_has_colors(): if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ: # Avoid importing curses that causes illegal operation # with a message: # PYTHON2 caused an invalid page fault in # module CYGNURSES7.DLL as 015f:18bbfc28 # Details: Python 2.3.3 [GCC 3.3.1 (cygming special)] # ssh to Win32 machine from debian # curses.version is 2.2 # CYGWIN_98-4.10, release 1.5.7(0.109/3/2)) return 0 if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(): try: import curses curses.setupterm() if (curses.tigetnum("colors") >= 0 and curses.tigetnum("pairs") >= 0 and ((curses.tigetstr("setf") is not None and curses.tigetstr("setb") is not None) or (curses.tigetstr("setaf") is not None and curses.tigetstr("setab") is not None) or curses.tigetstr("scp") is not None)): return 1 except Exception: pass return 0
def has_colours(stream): if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
def has_colours(stream): if not (hasattr(stream, "isatty") and stream.isatty()): return False try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # TODO: log console return False
def terminal_width(self): """Return the terminal width if possible, otherwise return 0. """ ncols = 0 try: import curses import io try: curses.setupterm() ncols = curses.tigetnum('cols') except AttributeError: # windows curses doesn't implement setupterm or tigetnum # code below from # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694 from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) ncols = right - left + 1 except curses.error: pass except io.UnsupportedOperation: pass except (ImportError, TypeError): pass return ncols
def get(cap, *args, **kwargs): default = kwargs.pop('default', '') if 'PWNLIB_NOTERM' in os.environ: return '' if kwargs != {}: raise TypeError("get(): No such argument %r" % kwargs.popitem()[0]) if cache == None: init() s = cache.get(cap) if not s: s = curses.tigetstr(cap) if s == None: s = curses.tigetnum(cap) if s == -2: s = curses.tigetflag(cap) if s == -1: # default to empty string so tparm doesn't fail s = '' else: s = bool(s) cache[cap] = s # if `s' is not set `curses.tparm' will throw an error if given arguments if args and s: return curses.tparm(s, *args) else: return s
def _verbose(self, message): BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) # following from Python cookbook, #475186 def has_colours(stream): if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False has_colours = has_colours(sys.stdout) def printout(text, colour=WHITE): if has_colours: seq = "\x1b[1;%dm" % (30 + colour) + text + "\x1b[0m\n" sys.stdout.write(seq) else: sys.stdout.write(text) if self.verboseMode: printout("hive-python: " + message, BLUE)
def has_colors(stream): '''Returns boolean indicating whether or not the supplied stream supports ANSI color. ''' if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
def enable_pretty_logging(): """Turns on formatted logging output as configured. This is called automatically by `parse_command_line`. """ root_logger = logging.getLogger() if options.log_file_prefix: channel = logging.handlers.RotatingFileHandler( filename=options.log_file_prefix, maxBytes=options.log_file_max_size, backupCount=options.log_file_num_backups) channel.setFormatter(_LogFormatter(color=False)) root_logger.addHandler(channel) if (options.log_to_stderr or (options.log_to_stderr is None and not root_logger.handlers)): # Set up color if we are in a tty and curses is installed color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except Exception: pass channel = logging.StreamHandler() channel.setFormatter(_LogFormatter(color=color)) root_logger.addHandler(channel)
def select_mod( choices: Sequence[Mod], header: Optional[str] = None, footer: Optional[str] = None, ) -> Optional[Mod]: """Present user with a TUI menu and return his choice. Keyword arguments: choices: The :class:`Mod`s to choose from. header: Optional menu heading. footer: Optional menu footing. Returns: The selected mod. """ menu = ModMenu(choices) head = urwid.Text(('title', header), align='center') if header else None foot = urwid.Text(('description', footer), align='center') if footer else None # noqa: E501 if head or foot: top = urwid.Frame(menu, head, foot) else: top = menu try: colors = curses.tigetnum('colors') except curses.error: # Uninitialized terminal colors = 16 event_loop = urwid.MainLoop( top, palette=ModMenu.palette, unhandled_input=exit_loop_on_q_esc, ) event_loop.screen.set_terminal_properties(colors=colors) event_loop.run() return menu.chosen
def _stderr_supports_color(): color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except Exception: pass return color