Python curses.tparm() Examples

The following are 30 code examples of curses.tparm(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module curses , or try the search function .
Example #1
Source File: ColorStreamHandler.py    From emailhunter-clone with MIT License 6 votes vote down vote up
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')

		# Get + Save the color sequences
		self.COLOR_INFO = curses.tparm(self.fcap, curses.COLOR_GREEN)
		self.COLOR_ERROR = curses.tparm(self.fcap, curses.COLOR_RED)
		self.COLOR_WARNING = curses.tparm(self.fcap, curses.COLOR_YELLOW)
		self.COLOR_DEBUG = curses.tparm(self.fcap, curses.COLOR_BLUE) 
Example #2
Source File: text.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def Render(self, target, foreground=None, background=None):
        """Decorate the string with the ansii escapes for the color."""
        if (not self.terminal_capable or
                foreground not in self.COLOR_MAP or
                background not in self.COLOR_MAP):
            return utils.SmartUnicode(target)

        escape_seq = ""
        if background:
            escape_seq += utils.SmartUnicode(self.tparm(
                ["setab", "setb"], self.COLOR_MAP[background]))

        if foreground:
            escape_seq += utils.SmartUnicode(self.tparm(
                ["setaf", "setf"], self.COLOR_MAP[foreground]))

        return (escape_seq + utils.SmartUnicode(target) +
                utils.SmartUnicode(self.tparm(["sgr0"]))) 
Example #3
Source File: run.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __missing__(self, key):
        # pylint: disable=unused-argument,no-self-use
        if not self.has_colors:
            return ''

        try:
            value = curses.tigetstr(self.attrs[key])
        except KeyError:
            try:
                value = curses.tparm(
                    curses.tigetstr('setaf'), self.colors.index(key))
            except ValueError:
                return ''

        value = value.decode()
        self[key] = value
        return value 
Example #4
Source File: formatters.py    From MARA_Framework with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __call__(self, *args):
        """P(*args) -> FormattingString()

        Return evaluated terminal capability (self), receiving arguments
        ``*args``, followed by the terminating sequence (self.normal) into
        a FormattingString capable of being called.
        """
        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.
            attr = curses.tparm(self.encode('latin1'), *args).decode('latin1')
            return FormattingString(attr, self._normal)
        except TypeError, err:
            # If the first non-int (i.e. incorrect) arg was a string, suggest
            # something intelligent:
            if len(args) and isinstance(args[0], basestring):
                raise TypeError(
                    "A native or nonexistent capability template, %r received"
                    " invalid argument %r: %s. You probably misspelled a"
                    " formatting call like `bright_red'" % (
                        self._name, args, err))
            # Somebody passed a non-string; I don't feel confident
            # guessing what they were trying to do.
            raise 
Example #5
Source File: log.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
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") 
Example #6
Source File: log.py    From pyftpdlib with MIT License 5 votes vote down vote up
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") 
Example #7
Source File: colorlog.py    From pySINDy with MIT License 5 votes vote down vote up
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 
Example #8
Source File: log.py    From script-languages with MIT License 5 votes vote down vote up
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") 
Example #9
Source File: ProgressBar.py    From alive with Apache License 2.0 5 votes vote down vote up
def _tparm(self, arg, index):
        import curses
        return curses.tparm(to_bytes(arg), index).decode('ascii') or '' 
Example #10
Source File: terminal.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
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 '') 
Example #11
Source File: log.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
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 = '' 
Example #12
Source File: options.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
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.  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 = {
                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") 
Example #13
Source File: screen.py    From asciimatics with Apache License 2.0 5 votes vote down vote up
def _print_at(self, text, x, y, width):
            """
            Print string at the required location.

            :param text: The text string to print.
            :param x: The x coordinate
            :param y: The Y coordinate
            :param width: The width of the character (for dual-width glyphs in CJK languages).
            """
            # Move the cursor if necessary
            cursor = u""
            if x != self._cur_x or y != self._cur_y:
                cursor = curses.tparm(self._move_y_x, y, x).decode("utf-8")

            # Print the text at the required location and update the current
            # position.
            try:
                self._safe_write(cursor + text)
            except UnicodeEncodeError:
                # This is probably a sign that the user has the wrong locale.
                # Try to soldier on anyway.
                self._safe_write(cursor + "?" * len(text))

            # Update cursor position for next time...
            self._cur_x = x + width
            self._cur_y = y 
Example #14
Source File: log.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
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") 
Example #15
Source File: screen.py    From asciimatics with Apache License 2.0 5 votes vote down vote up
def _change_colours(self, colour, attr, bg):
            """
            Change current colour if required.

            :param colour: New colour to use.
            :param attr: New attributes to use.
            :param bg: New background colour to use.
            """
            # Change attribute first as this will reset colours when swapping
            # modes.
            if attr != self._attr:
                self._safe_write(self._a_normal)
                if attr != 0:
                    self._safe_write(self._ATTRIBUTES[attr])
                self._attr = attr
                self._colour = None
                self._bg = None

            # Now swap colours if required.
            if colour != self._colour:
                self._safe_write(curses.tparm(
                    self._fg_color, colour).decode("utf-8"))
                self._colour = colour
            if bg != self._bg:
                self._safe_write(curses.tparm(
                    self._bg_color, bg).decode("utf-8"))
                self._bg = bg 
Example #16
Source File: log.py    From oss-ftp with MIT License 5 votes vote down vote up
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") 
Example #17
Source File: log.py    From oss-ftp with MIT License 5 votes vote down vote up
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") 
Example #18
Source File: shell.py    From python-igraph with GNU General Public License v2.0 5 votes vote down vote up
def _tparm(cap_name, param):
        import curses
        cap = curses.tparm(cap_name.encode("latin-1"), param) or b''
        return cap.decode("latin-1") 
Example #19
Source File: diagram.py    From diagram with MIT License 5 votes vote down vote up
def csi(self, capname, *args):
        """Return the escape sequence for the selected Control Sequence."""
        value = curses.tigetstr(capname)
        if value is None:
            return b''
        else:
            return curses.tparm(value, *args) 
Example #20
Source File: options.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
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") 
Example #21
Source File: screen.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def _print_at(self, text, x, y, width):
            """
            Print string at the required location.

            :param text: The text string to print.
            :param x: The x coordinate
            :param y: The Y coordinate
            :param width: The width of the character (for dual-width glyphs in CJK languages).
            """
            # Move the cursor if necessary
            cursor = u""
            if x != self._cur_x or y != self._cur_y:
                cursor = curses.tparm(self._move_y_x, y, x).decode("utf-8")

            # Print the text at the required location and update the current
            # position.
            try:
                self._safe_write(cursor + text)
            except UnicodeEncodeError:
                # This is probably a sign that the user has the wrong locale.
                # Try to soldier on anyway.
                self._safe_write(cursor + "?" * len(text))

            # Update cursor position for next time...
            self._cur_x = x + width
            self._cur_y = y 
Example #22
Source File: screen.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def _change_colours(self, colour, attr, bg):
            """
            Change current colour if required.

            :param colour: New colour to use.
            :param attr: New attributes to use.
            :param bg: New background colour to use.
            """
            # Change attribute first as this will reset colours when swapping
            # modes.
            if attr != self._attr:
                self._safe_write(self._a_normal)
                if attr != 0:
                    self._safe_write(self._ATTRIBUTES[attr])
                self._attr = attr
                self._colour = None
                self._bg = None

            # Now swap colours if required.
            if colour != self._colour:
                self._safe_write(curses.tparm(
                    self._fg_color, colour).decode("utf-8"))
                self._colour = colour
            if bg != self._bg:
                self._safe_write(curses.tparm(
                    self._bg_color, bg).decode("utf-8"))
                self._bg = bg 
Example #23
Source File: formatters.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __new__(cls, *args):
        """P.__new__(cls, cap, [normal, [name]])

        :arg cap: parameterized string suitable for curses.tparm()
        :arg normal: terminating sequence for this capability.
        :arg name: name of this terminal capability.
        """
        assert len(args) and len(args) < 4, args
        new = unicode.__new__(cls, args[0])
        new._normal = len(args) > 1 and args[1] or u''
        new._name = len(args) > 2 and args[2] or u'<not specified>'
        return new 
Example #24
Source File: formatters.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, *args):
        """Return a Unicode or whatever you passed in as the first arg
        (hopefully a string of some kind).

        When called with an int as the first arg, return an empty Unicode. An
        int is a good hint that I am a ``ParameterizingString``, as there are
        only about half a dozen string-returning capabilities listed in
        terminfo(5) which accept non-int arguments, they are seldom used.

        When called with a non-int as the first arg (no no args at all), return
        the first arg, acting in place of ``FormattingString`` without
        any attributes.
        """
        if len(args) != 1 or isinstance(args[0], int):
            # I am acting as a ParameterizingString.

            # tparm can take not only ints but also (at least) strings as its
            # 2nd...nth argument. But we don't support callable parameterizing
            # capabilities that take non-ints yet, so we can cheap out here.

            # TODO(erikrose): Go through enough of the motions in the
            # capability resolvers to determine which of 2 special-purpose
            # classes, NullParameterizableString or NullFormattingString,
            # to return, and retire this one.

            # As a NullCallableString, even when provided with a parameter,
            # such as t.color(5), we must also still be callable, fe:
            #
            # >>> t.color(5)('shmoo')
            #
            # is actually simplified result of NullCallable()() on terminals
            # without color support, so turtles all the way down: we return
            # another instance.
            return NullCallableString()
        return args[0] 
Example #25
Source File: accessories.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def unicode_parm(cap, *parms):
    """Return the result of ``tparm(tigetstr())`` except as Unicode."""
    cap = curses.tigetstr(cap)
    if cap:
        val = curses.tparm(cap, *parms)
        if val:
            return val.decode('latin1')
    return u'' 
Example #26
Source File: tests.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def unicode_parm(cap, *parms):
    """Return the result of ``tparm(tigetstr())`` except as Unicode."""
    return tparm(tigetstr(cap), *parms).decode('latin1') 
Example #27
Source File: __init__.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, *args):
        """Return a Unicode or whatever you passed in as the first arg
        (hopefully a string of some kind).

        When called with an int as the first arg, return an empty Unicode. An
        int is a good hint that I am a ``ParametrizingString``, as there are
        only about half a dozen string-returning capabilities on OS X's
        terminfo man page which take any param that's not an int, and those are
        seldom if ever used on modern terminal emulators. (Most have to do with
        programming function keys. Blessings' story for supporting
        non-string-returning caps is undeveloped.) And any parametrized
        capability in a situation where all capabilities themselves are taken
        to be blank are, of course, themselves blank.

        When called with a non-int as the first arg (no no args at all), return
        the first arg. I am acting as a ``FormattingString``.

        """
        if len(args) != 1 or isinstance(args[0], int):
            # I am acting as a ParametrizingString.

            # tparm can take not only ints but also (at least) strings as its
            # second...nth args. But we don't support callably parametrizing
            # caps that take non-ints yet, so we can cheap out here. TODO: Go
            # through enough of the motions in the capability resolvers to
            # determine which of 2 special-purpose classes,
            # NullParametrizableString or NullFormattingString, to return, and
            # retire this one.
            return u''
        return args[0]  # Should we force even strs in Python 2.x to be
                        # unicodes? No. How would I know what encoding to use
                        # to convert it? 
Example #28
Source File: doctest_driver.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, term_stream=sys.stdout):
        # If the stream isn't a tty, then assume it has no capabilities.
        if not term_stream.isatty(): return
        if self.FORCE_SIMPLE_TERM: return

        # Curses isn't available on all platforms
        try: import curses
        except:
            # If it's not available, then try faking enough to get a
            # simple progress bar.
            self.BOL = '\r'
            self.CLEAR_LINE = '\r' + ' '*self.COLS + '\r'
            
        # 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')
        
        # Look up string capabilities.
        for capability in self._STRING_CAPABILITIES:
            (attrib, cap_name) = capability.split('=')
            setattr(self, attrib, self._tigetstr(cap_name) or '')
        if self.BOL and self.CLEAR_EOL:
            self.CLEAR_LINE = self.BOL+self.CLEAR_EOL

        # Colors
        set_fg = self._tigetstr('setf')
        if set_fg:
            for i,color in enumerate(self._COLORS):
                setattr(self, color, curses.tparm(set_fg, i) or '')
        set_fg_ansi = self._tigetstr('setaf')
        if set_fg_ansi:
            for i,color in enumerate(self._ANSICOLORS):
                setattr(self, color, curses.tparm(set_fg_ansi, i) or '') 
Example #29
Source File: screen.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def _scroll(self, lines):
            """
            Scroll the window up or down.

            :param lines: Number of lines to scroll.  Negative numbers scroll
                down.
            """
            if lines < 0:
                self._safe_write("{}{}".format(
                    curses.tparm(self._move_y_x, 0, 0).decode("utf-8"),
                    (self._up_line + self._clear_line) * -lines))
            else:
                self._safe_write("{}{}".format(curses.tparm(
                    self._move_y_x, self.height, 0).decode("utf-8"),
                    (self._down_line + self._clear_line) * lines)) 
Example #30
Source File: log_utils.py    From style_transfer with MIT License 5 votes vote down vote up
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 = ''