我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.tigetstr()。
def __init__(self): self.data = [] self.has_ipython = True self.display_type = "multi" self.global_data_size = 0 self.global_val_data_size = 0 self.snapped = False global CURSES_SUPPORTED if CURSES_SUPPORTED: try: curses.setupterm() sys.stdout.write(curses.tigetstr('civis').decode()) except Exception: CURSES_SUPPORTED = False try: clear_output except NameError: self.has_ipython = False
def __init__(self, color, *args, **kwargs): logging.Formatter.__init__(self, *args, **kwargs) self._color = color if color: # The curses module has some str/bytes confusion in python3. # Most methods return bytes, but only accept strings. # The explict calls to unicode() below are harmless in python2, # but will do the right conversion in python3. fg_color = unicode(curses.tigetstr("setaf") or curses.tigetstr("setf") or "", "ascii") self._colors = { logging.DEBUG: unicode(curses.tparm(fg_color, 4), # Blue "ascii"), logging.INFO: unicode(curses.tparm(fg_color, 2), # Green "ascii"), logging.WARNING: unicode(curses.tparm(fg_color, 3), # Yellow "ascii"), logging.ERROR: unicode(curses.tparm(fg_color, 1), # Red "ascii"), } self._normal = unicode(curses.tigetstr("sgr0"), "ascii")
def __init__(self, use_colors): logging.Handler.__init__(self) self.use_colors = use_colors # Initialize environment curses.setupterm() # Get the foreground color attribute for this environment self.fcap = curses.tigetstr('setaf') # Get the normal attribute self.COLOR_NORMAL = curses.tigetstr('sgr0').decode("utf-8") # Get + Save the color sequences self.COLOR_INFO = curses.tparm(self.fcap, curses.COLOR_GREEN).decode("utf-8") self.COLOR_ERROR = curses.tparm(self.fcap, curses.COLOR_RED).decode("utf-8") self.COLOR_WARNING = curses.tparm(self.fcap, curses.COLOR_YELLOW).decode("utf-8") self.COLOR_DEBUG = curses.tparm(self.fcap, curses.COLOR_BLUE).decode("utf-8")
def __init__(self, stream, charset=None): # our Enterprise logic follows self.stream_isatty = stream.isatty() if charset is None: charset = ENTERPRISE_CHARSET if self.stream_isatty else '.' super(QubesSpinnerEnterpriseEdition, self).__init__(stream, charset) if self.stream_isatty: try: curses.setupterm() self.has_terminfo = True self.cub1 = curses.tigetstr('cub1').decode() except (curses.error, io.UnsupportedOperation): # we are in very non-Enterprise environment self.has_terminfo = False else: self.cub1 = ''
def resolve_capability(term, attr): """ Resolve a raw terminal capability using :func:`tigetstr`. :arg Terminal term: :class:`~.Terminal` instance. :arg str attr: terminal capability name. :returns: string of the given terminal capability named by ``attr``, which may be empty (u'') if not found or not supported by the given :attr:`~.Terminal.kind`. :rtype: str """ # Decode sequences as latin1, as they are always 8-bit bytes, so when # b'\xff' is returned, this must be decoded to u'\xff'. if not term.does_styling: return u'' val = curses.tigetstr(term._sugar.get(attr, attr)) return u'' if val is None else val.decode('latin1')
def __init__(self, color, *args, **kwargs): logging.Formatter.__init__(self, *args, **kwargs) self._color = color if color: fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = six.text_type(fg_color, "ascii") self._colors = { logging.DEBUG: six.text_type(curses.tparm(fg_color, 4), "ascii"), # Blue logging.INFO: six.text_type(curses.tparm(fg_color, 2), "ascii"), # Green logging.WARNING: six.text_type(curses.tparm(fg_color, 3), "ascii"), # Yellow logging.ERROR: six.text_type(curses.tparm(fg_color, 1), "ascii"), # Red } self._normal = six.text_type(curses.tigetstr("sgr0"), "ascii")
def setterm(self, term): "Set the curses structures for this terminal" self.logging.debug("Setting termtype to %s" % (term, )) curses.setupterm(term) # This will raise if the termtype is not supported self.TERM = term self.ESCSEQ = {} for k in self.KEYS.keys(): str = curses.tigetstr(curses.has_key._capability_names[k]) if str: self.ESCSEQ[str] = k #maybe in windows, use a hardcode seq if self.ESCSEQ.get('\x1b[D') is None: self.ESCSEQ = {'\x08' : 263, '\x1b[D' : 260, '\x1b[A' : 259, '\x1b[C' : 261, '\x1b[B' : 258} self.CODES['DEOL'] = curses.tigetstr('el') self.CODES['DEL'] = curses.tigetstr('dch1') self.CODES['INS'] = curses.tigetstr('ich1') self.CODES['CSRLEFT'] = curses.tigetstr('cub1') self.CODES['CSRRIGHT'] = curses.tigetstr('cuf1') if self.CODES.get('CSRLEFT') is None: self.CODES = {'CSRLEFT' : '\x1b[D', 'DEL' : '\x1b[P', 'CSRRIGHT' : '\x1b[C', 'DEOL' : '\x1b[K', 'INS' : None}
def _tigetstr(self, cap_name): # String capabilities can include "delays" of the form "$<2>". # For any modern terminal, we should be able to just ignore # these, so strip them out. import curses cap = curses.tigetstr(cap_name) or '' return re.sub(r'\$<\d+>[/*]?', '', cap)
def clear_screen(): import curses, sys curses.setupterm() sys.stdout.write(curses.tigetstr("clear")) sys.stdout.flush()
def __init__(self, color=True, fmt=DEFAULT_FORMAT, datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS): r""" :arg bool color: Enables color support. :arg string fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. :arg dict colors: color mappings from logging level to terminal color code :arg string datefmt: Datetime format. Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``. .. versionchanged:: 3.2 Added ``fmt`` and ``datefmt`` arguments. """ logging.Formatter.__init__(self, datefmt=datefmt) self._fmt = fmt self._colors = {} if color and _stderr_supports_color(): # The curses module has some str/bytes confusion in # python3. Until version 3.2.3, most methods return # bytes, but only accept strings. In addition, we want to # output these strings with the logging module, which # works with unicode strings. The explicit calls to # unicode() below are harmless in python2 but will do the # right conversion in python 3. fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = unicode_type(fg_color, "ascii") for levelno, code in colors.items(): self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), "ascii") self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii") else: self._normal = ''
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 on_train_end(self, training_state): # Reset caret to last position to_be_printed = "" if CURSES_SUPPORTED: #if not self.has_ipython #TODO:check bug here for i in range(len(self.data) + 2): to_be_printed += "\033[B" if not self.snapped: to_be_printed += "--\n" sys.stdout.write(to_be_printed) sys.stdout.flush() # Set caret visible if possible if CURSES_SUPPORTED: sys.stdout.write(curses.tigetstr('cvvis').decode())
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 __init__(self, color=True, fmt=DEFAULT_FORMAT, datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS, precision=3): r""" :arg bool color: Enables color support. :arg string fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. :arg dict colors: color mappings from logging level to terminal color code :arg string datefmt: Datetime format. Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``. .. versionchanged:: 3.2 Added ``fmt`` and ``datefmt`` arguments. """ super().__init__() self.default_time_format = datefmt self.precision = precision self.default_msec_format = '' self._fmt = fmt self._colors = {} if color and _stderr_supports_color(): fg_color = (curses.tigetstr('setaf') or curses.tigetstr('setf') or '') for levelno, code in colors.items(): self._colors[levelno] = curses.tparm(fg_color, code).decode() self._normal = curses.tigetstr('sgr0').decode() else: self._normal = ''
def __init__(self, color=True, datefmt=None): r""" :arg bool color: Enables color support. :arg string fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. :arg dict colors: color mappings from logging level to terminal color code :arg string datefmt: Datetime format. Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``. .. versionchanged:: 3.2 Added ``fmt`` and ``datefmt`` arguments. """ logging.Formatter.__init__(self, datefmt=datefmt) self._colors = {} if color and _stderr_supports_color(): # The curses module has some str/bytes confusion in # python3. Until version 3.2.3, most methods return # bytes, but only accept strings. In addition, we want to # output these strings with the logging module, which # works with unicode strings. The explicit calls to # unicode() below are harmless in python2 but will do the # right conversion in python 3. fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = str(fg_color, "ascii") for levelno, code in self.DEFAULT_COLORS.items(): self._colors[levelno] = str(curses.tparm(fg_color, code), "ascii") self._normal = str(curses.tigetstr("sgr0"), "ascii") scr = curses.initscr() self.termwidth = scr.getmaxyx()[1] curses.endwin() else: self._normal = '' # Default width is usually 80, but too wide is worse than too narrow self.termwidth = 70
def __init__(self): """ Initialization """ dict.__init__(self, { 'NORMAL': '', 'BOLD': '', 'ERASE': '\n', 'RED': '', 'YELLOW': '', 'GREEN': '', }) try: import curses as _curses except ImportError: # fixup if a submodule of curses failed. if 'curses' in _sys.modules: del _sys.modules['curses'] else: try: _curses.setupterm() except (TypeError, _curses.error): pass else: def make_color(color): """ Make color control string """ seq = _curses.tigetstr('setaf') if seq is not None: seq = _curses.tparm(seq, color) return seq self['NORMAL'] = _curses.tigetstr('sgr0') self['BOLD'] = _curses.tigetstr('bold') erase = _curses.tigetstr('el1') if erase is not None: self['ERASE'] = erase + _curses.tigetstr('cr') self['RED'] = make_color(_curses.COLOR_RED) self['YELLOW'] = make_color(_curses.COLOR_YELLOW) self['GREEN'] = make_color(_curses.COLOR_GREEN)
def __init__(self, color, *args, **kwargs): logging.Formatter.__init__(self, *args, **kwargs) self._color = color if color: fg_color = curses.tigetstr("setaf") or curses.tigetstr("setf") or "" self._colors = { logging.DEBUG: curses.tparm(fg_color, 4), # Blue logging.INFO: curses.tparm(fg_color, 2), # Green logging.WARNING: curses.tparm(fg_color, 3), # Yellow logging.ERROR: curses.tparm(fg_color, 1), # Red } self._normal = curses.tigetstr("sgr0")
def unicode_cap(cap): """Return the result of ``tigetstr`` except as Unicode.""" return tigetstr(cap).decode('latin1')
def unicode_parm(cap, *parms): """Return the result of ``tparm(tigetstr())`` except as Unicode.""" return tparm(tigetstr(cap), *parms).decode('latin1')
def _resolve_capability(self, atom): """Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings. """ code = tigetstr(self._sugar.get(atom, atom)) if code: # See the comment in ParametrizingString for why this is latin1. return code.decode('latin1') return ''
def __call__(self, *args): try: # Re-encode the cap, because tparm() takes a bytestring in Python # 3. However, appear to be a plain Unicode string otherwise so # concats work. # # We use *latin1* encoding so that bytes emitted by tparm are # encoded to their native value: some terminal kinds, such as # 'avatar' or 'kermit', emit 8-bit bytes in range 0x7f to 0xff. # latin1 leaves these values unmodified in their conversion to # unicode byte values. The terminal emulator will "catch" and # handle these values, even if emitting utf8-encoded text, where # these bytes would otherwise be illegal utf8 start bytes. parametrized = tparm(self.encode('latin1'), *args).decode('latin1') return (parametrized if self._normal is None else FormattingString(parametrized, self._normal)) except curses.error: # Catch "must call (at least) setupterm() first" errors, as when # running simply `nosetests` (without progressive) on nose- # progressive. Perhaps the terminal has gone away between calling # tigetstr and calling tparm. return '' except TypeError: # If the first non-int (i.e. incorrect) arg was a string, suggest # something intelligent: if len(args) == 1 and isinstance(args[0], str): raise TypeError( 'A native or nonexistent capability template received ' '%r when it was expecting ints. You probably misspelled a ' 'formatting call like bright_red_on_white(...).' % args) else: # Somebody passed a non-string; I don't feel confident # guessing what they were trying to do. raise
def hide(self): if self.stream_isatty: hideseq = '\r' + ' ' * self.hidelen + '\r' if self.has_terminfo: hideseq_l = (curses.tigetstr('cr'), curses.tigetstr('clr_eol')) if all(seq is not None for seq in hideseq_l): hideseq = ''.join(seq.decode() for seq in hideseq_l) else: hideseq = '\n' self.stream.write(hideseq) self.stream.flush()
def __init__(self, color=True, *args, **kwargs): logging.Formatter.__init__(self, *args, **kwargs) self._color = color and _stderr_supports_color() if self._color: # The curses module has some str/bytes confusion in # python3. Until version 3.2.3, most methods return # bytes, but only accept strings. In addition, we want to # output these strings with the logging module, which # works with unicode strings. The explicit calls to # unicode() below are harmless in python2 but will do the # right conversion in python 3. fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = unicode_type(fg_color, "ascii") self._colors = { logging.DEBUG: unicode_type(curses.tparm(fg_color, 4), # Blue "ascii"), logging.INFO: unicode_type(curses.tparm(fg_color, 2), # Green "ascii"), logging.WARNING: unicode_type(curses.tparm(fg_color, 3), # Yellow "ascii"), logging.ERROR: unicode_type(curses.tparm(fg_color, 1), # Red "ascii"), } self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
def __init__(self, *args, **kwargs): logging.Formatter.__init__(self, *args, **kwargs) self._coloured = COLOURED and _stderr_supports_color() if self._coloured: curses.setupterm() # The curses module has some str/bytes confusion in # python3. Until version 3.2.3, most methods return # bytes, but only accept strings. In addition, we want to # output these strings with the logging module, which # works with unicode strings. The explicit calls to # unicode() below are harmless in python2 but will do the # right conversion in python 3. fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = unicode(fg_color, "ascii") self._colors = { # blues logging.DEBUG: unicode(curses.tparm(fg_color, 4), "ascii"), # green logging.INFO: unicode(curses.tparm(fg_color, 2), "ascii"), # yellow logging.WARNING: unicode(curses.tparm(fg_color, 3), "ascii"), # red logging.ERROR: unicode(curses.tparm(fg_color, 1), "ascii") } self._normal = unicode(curses.tigetstr("sgr0"), "ascii")
def __init__(self, color, *args, **kwargs): logging.Formatter.__init__(self, *args, **kwargs) self._color = color if color: fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = six.text_type(fg_color, "ascii") self._colors = { logging.DEBUG: six.text_type( curses.tparm(fg_color, 4), "ascii" ), # Blue logging.INFO: six.text_type( curses.tparm(fg_color, 2), "ascii" ), # Green logging.WARNING: six.text_type( curses.tparm(fg_color, 3), "ascii" ), # Yellow logging.ERROR: six.text_type( curses.tparm(fg_color, 1), "ascii" ), # Red } self._normal = six.text_type(curses.tigetstr("sgr0"), "ascii")
def _resolve_capability(self, atom): """Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings. """ code = tigetstr(self._sugar.get(atom, atom)) if code: # See the comment in ParametrizingString for why this is latin1. return code.decode('latin1') return u''
def __call__(self, *args): try: # Re-encode the cap, because tparm() takes a bytestring in Python # 3. However, appear to be a plain Unicode string otherwise so # concats work. # # We use *latin1* encoding so that bytes emitted by tparm are # encoded to their native value: some terminal kinds, such as # 'avatar' or 'kermit', emit 8-bit bytes in range 0x7f to 0xff. # latin1 leaves these values unmodified in their conversion to # unicode byte values. The terminal emulator will "catch" and # handle these values, even if emitting utf8-encoded text, where # these bytes would otherwise be illegal utf8 start bytes. parametrized = tparm(self.encode('latin1'), *args).decode('latin1') return (parametrized if self._normal is None else FormattingString(parametrized, self._normal)) except curses.error: # Catch "must call (at least) setupterm() first" errors, as when # running simply `nosetests` (without progressive) on nose- # progressive. Perhaps the terminal has gone away between calling # tigetstr and calling tparm. return u'' except TypeError: # If the first non-int (i.e. incorrect) arg was a string, suggest # something intelligent: if len(args) == 1 and isinstance(args[0], basestring): raise TypeError( 'A native or nonexistent capability template received ' '%r when it was expecting ints. You probably misspelled a ' 'formatting call like bright_red_on_white(...).' % args) else: # Somebody passed a non-string; I don't feel confident # guessing what they were trying to do. raise
def activate(self): # Hide cursor curses.setupterm() sys.stderr.buffer.write(curses.tigetstr('civis')) self.update(self._pos) self._activated = True
def done(self): # Force update to last known pos, in case it wasn't printed due to the threshold self.update(self._pos, force=True) sys.stderr.write('\n') # Restore cursor sys.stderr.buffer.write(curses.tigetstr('cnorm')) self._activated = False