Python curses 模块,setupterm() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.setupterm()

项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:tflearn    作者:tflearn    | 项目源码 | 文件源码
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
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:OpenDoor    作者:stanislav-web    | 项目源码 | 文件源码
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
项目:ryu-lagopus-ext    作者:lagopus    | 项目源码 | 文件源码
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
项目:annotated-py-tornado    作者:hhstore    | 项目源码 | 文件源码
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)
项目:SFT    作者:xumi1993    | 项目源码 | 文件源码
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
项目:SFT    作者:xumi1993    | 项目源码 | 文件源码
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
项目:danmu.fm    作者:twocucao    | 项目源码 | 文件源码
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")
项目:nova-lxd    作者:openstack    | 项目源码 | 文件源码
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
项目:mccurse    作者:khardix    | 项目源码 | 文件源码
def cli(ctx, quiet, refresh):
    """Unofficial CLI client for Minecraft Curse Forge."""

    # Context for the subcommands
    ctx.obj = {
        'default_game': Game.find('Minecraft'),  # Default game to query and use
        'token_path': default_data_dir() / 'token.yaml',  # Authorization token location
    }

    # Common setup

    # Setup terminal for querying (number of colors, etc.)
    curses.setupterm()
    # Setup appropriate logging level
    log.setLevel(INFO if not quiet else ERROR)

    # Refresh game data if necessary
    if refresh or not ctx.obj['default_game'].have_fresh_data():
        log.info(_('Refreshing game data, please wait.'))
        ctx.obj['default_game'].refresh_data()
项目:qubes-core-admin-client    作者:QubesOS    | 项目源码 | 文件源码
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 = ''
项目:ranger-agent    作者:openstack    | 项目源码 | 文件源码
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
项目:AsyncFTP    作者:helloqiu    | 项目源码 | 文件源码
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)
项目:minihydra    作者:VillanCh    | 项目源码 | 文件源码
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
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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
项目:oejia_wx    作者:JoneXiong    | 项目源码 | 文件源码
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)
项目:ansible-role-elk-kibana    作者:jpnewman    | 项目源码 | 文件源码
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
项目:rpcDemo    作者:Tangxinwei    | 项目源码 | 文件源码
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}
项目:deb-ryu    作者:openstack    | 项目源码 | 文件源码
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
项目:LIS-Tempest    作者:LIS    | 项目源码 | 文件源码
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
项目:stestr    作者:mtreinish    | 项目源码 | 文件源码
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
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
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
项目:rxjavademo    作者:BaoBaoJianqiang    | 项目源码 | 文件源码
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
项目:Bahubali---DDOS-Toolkit    作者:navanchauhan    | 项目源码 | 文件源码
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 '')
项目:WPForce    作者:n00py    | 项目源码 | 文件源码
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
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def clear_screen():
    import curses, sys
    curses.setupterm()
    sys.stdout.write(curses.tigetstr("clear"))
    sys.stdout.flush()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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
项目:radar    作者:amoose136    | 项目源码 | 文件源码
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
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
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
项目:os4tw    作者:mattiareggiani    | 项目源码 | 文件源码
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
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
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
项目:pwndemo    作者:zh-explorer    | 项目源码 | 文件源码
def init():
    global cache

    if 'PWNLIB_NOTERM' not in os.environ:
        # Fix for BPython
        try:
            curses.setupterm()
        except:
            pass

    cache = {}
项目:style_transfer    作者:crowsonkb    | 项目源码 | 文件源码
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
项目:pep517    作者:pypa    | 项目源码 | 文件源码
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
项目:My-Web-Server-Framework-With-Python2.7    作者:syjsu    | 项目源码 | 文件源码
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
项目:hive    作者:tdeheurles    | 项目源码 | 文件源码
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)
项目:pssh    作者:lilydjwg    | 项目源码 | 文件源码
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
项目:time2go    作者:twitchyliquid64    | 项目源码 | 文件源码
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)
项目:deb-python-rjsmin    作者:openstack    | 项目源码 | 文件源码
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)
项目:nwjs-ffmpeg-prebuilt    作者:iteufel    | 项目源码 | 文件源码
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
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
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
项目:annotated-py-tornado    作者:hhstore    | 项目源码 | 文件源码
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
项目:annotated-py-tornado    作者:hhstore    | 项目源码 | 文件源码
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
项目:annotated-py-tornado    作者:hhstore    | 项目源码 | 文件源码
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
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
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
项目:SFT    作者:xumi1993    | 项目源码 | 文件源码
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