python类setupterm()的实例源码

reporter.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
callbacks.py 文件源码 项目:tflearn 作者: tflearn 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
reporter.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
color.py 文件源码 项目:OpenDoor 作者: stanislav-web 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
test_lib.py 文件源码 项目:ryu-lagopus-ext 作者: lagopus 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def supported(cls, stream=sys.stdout):
        """
        A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False  # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except:
                # guess false in case of error
                return False
options.py 文件源码 项目:annotated-py-tornado 作者: hhstore 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:SFT 作者: xumi1993 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:SFT 作者: xumi1993 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
color_stream_handler.py 文件源码 项目:danmu.fm 作者: twocucao 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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")
colorizer.py 文件源码 项目:nova-lxd 作者: openstack 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def supported(cls, stream=sys.stdout):
        """A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False  # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except Exception:
                # guess false in case of error
                return False
cli.py 文件源码 项目:mccurse 作者: khardix 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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()
spinner.py 文件源码 项目:qubes-core-admin-client 作者: QubesOS 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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 = ''
colorizer.py 文件源码 项目:ranger-agent 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
Logger.py 文件源码 项目:AsyncFTP 作者: helloqiu 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:minihydra 作者: VillanCh 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
reporter.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def supported(cls, stream=sys.stdout):
        """
        A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except:
                # guess false in case of error
                return False
logger.py 文件源码 项目:oejia_wx 作者: JoneXiong 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
sync_kibana_objects.py 文件源码 项目:ansible-role-elk-kibana 作者: jpnewman 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
telnetsrvlib.py 文件源码 项目:rpcDemo 作者: Tangxinwei 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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}
test_lib.py 文件源码 项目:deb-ryu 作者: openstack 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def supported(cls, stream=sys.stdout):
        """
        A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False  # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except:
                # guess false in case of error
                return False
colorizer.py 文件源码 项目:LIS-Tempest 作者: LIS 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def supported(cls, stream=sys.stdout):
        """
        A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False  # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except Exception:
                # guess false in case of error
                return False
colorizer.py 文件源码 项目:stestr 作者: mtreinish 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
colorizer.py 文件源码 项目:Trusted-Platform-Module-nova 作者: BU-NU-CLOUD-SP16 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def supported(cls, stream=sys.stdout):
        """A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False  # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except Exception:
                # guess false in case of error
                return False
terminal.py 文件源码 项目:rxjavademo 作者: BaoBaoJianqiang 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
terminal.py 文件源码 项目:Bahubali---DDOS-Toolkit 作者: navanchauhan 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:WPForce 作者: n00py 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def has_colours(stream):
    if not hasattr(stream, "isatty"):
        return False
    if not stream.isatty():
        return False # auto color only on TTYs
    try:
        import curses
        curses.setupterm()
        return curses.tigetnum("colors") > 2
    except:
        return False
recipe-498064.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def clear_screen():
    import curses, sys
    curses.setupterm()
    sys.stdout.write(curses.tigetstr("clear"))
    sys.stdout.flush()
log.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
log.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
log.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号