def _lookup_caps(): import curses from .utils import to_ascii # Look up numeric capabilities. colors.COLS = curses.tigetnum('cols') colors.LINES = curses.tigetnum('lines') # Look up string capabilities. for capability in _STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(colors, attrib, _tigetstr(cap_name) or '') # Colors set_fg = _tigetstr('setf') if set_fg: for i, color in zip(list(range(len(_COLORS))), _COLORS): setattr(colors, color, to_ascii(curses.tparm(set_fg.encode('utf-8'), i)) or '') set_fg_ansi = _tigetstr('setaf') if set_fg_ansi: for i, color in zip(list(range(len(_ANSICOLORS))), _ANSICOLORS): setattr(colors, color, to_ascii(curses.tparm(set_fg_ansi.encode('utf-8'), i)) or '') set_bg = _tigetstr('setb') if set_bg: for i, color in zip(list(range(len(_COLORS))), _COLORS): setattr(colors, 'BG_'+color, to_ascii(curses.tparm(set_bg.encode('utf-8'), i)) or '') set_bg_ansi = _tigetstr('setab') if set_bg_ansi: for i, color in zip(list(range(len(_ANSICOLORS))), _ANSICOLORS): setattr(colors, 'BG_'+color, to_ascii(curses.tparm(set_bg_ansi.encode('utf-8'), i)) or '')
def run(self): while True: self.render_screen() c = self.screen.getch() if c == curses.KEY_UP or c == self.KEY_k: self.updown(-1) elif c == curses.KEY_DOWN or c == self.KEY_j: self.updown(1) elif c == self.KEY_u: for i in range(0, curses.tigetnum('lines')): self.updown(-1) elif c == self.KEY_d: for i in range(0, curses.tigetnum('lines')): self.updown(1) elif c == self.KEY_ENTER or c == self.KEY_SPACE: self.toggle_node() elif c == self.KEY_ESC or c == self.KEY_q: self.exit() elif c == self.KEY_O or c == self.KEY_M: self.open_all() elif c == self.KEY_o or c == self.KEY_m: self.open_node() elif c == self.KEY_C or c == self.KEY_R: self.close_all() elif c == self.KEY_c or c == self.KEY_r: self.close_node() elif c == self.KEY_g: self.page_top() elif c == self.KEY_G: self.page_bottom() elif c == self.KEY_SPLASH: self.enter_search_mode()
def terminal_has_colors(): if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ: # Avoid importing curses that causes illegal operation # with a message: # PYTHON2 caused an invalid page fault in # module CYGNURSES7.DLL as 015f:18bbfc28 # Details: Python 2.3.3 [GCC 3.3.1 (cygming special)] # ssh to Win32 machine from debian # curses.version is 2.2 # CYGWIN_98-4.10, release 1.5.7(0.109/3/2)) return 0 if hasattr(sys.stdout,'isatty') and sys.stdout.isatty(): try: import curses curses.setupterm() if (curses.tigetnum("colors") >= 0 and curses.tigetnum("pairs") >= 0 and ((curses.tigetstr("setf") is not None and curses.tigetstr("setb") is not None) or (curses.tigetstr("setaf") is not None and curses.tigetstr("setab") is not None) or curses.tigetstr("scp") is not None)): return 1 except Exception: pass return 0
def get_term_size(): """ Get the number of lines and columns of the tty that is connected to stdout. Returns a tuple of (lines, columns) or (0, 0) if an error occurs. The curses module is used if available, otherwise the output of `stty size` is parsed. The lines and columns values are guaranteed to be greater than or equal to zero, since a negative COLUMNS variable is known to prevent some commands from working (see bug #394091). """ if not sys.stdout.isatty(): return (0, 0) try: import curses try: curses.setupterm() return curses.tigetnum('lines'), curses.tigetnum('cols') except curses.error: pass except ImportError: pass st, out = portage.subprocess_getstatusoutput('stty size') if st == os.EX_OK: out = out.split() if len(out) == 2: try: val = (int(out[0]), int(out[1])) except ValueError: pass else: if val[0] >= 0 and val[1] >= 0: return val return (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 Error: 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 Error: return # Look up numeric capabilities. # return -2 if capname is not a numberic capability # return -1 if it is canceled or absent from terminal description 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') # curses.tparm instantiates the string with the supplied parameters, # where str should be a parameterized string obtained from the terminfo # database. E.g tparm(tigetstr("cup", 5, 3) could result in # '\033[6;4H', the exact result depending on terminal type if set_fg: for index, color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, curses.tparm(set_fg, index) or '') set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for index, color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, curses.tparm(set_fg_ansi, index) or '') set_bg = self._tigetstr('setb') if set_bg: for index, color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, 'BG_'+color, curses.tparm(set_bg, index) or '') set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: for index, color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, 'BG_'+color, curses.tparm(set_bg_ansi, index) or '')
def initcurse(self): # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm() except: return #self.colors = cursescolors() self.cols = curses.tigetnum('cols') self.lines = curses.tigetnum('lines') self.wfilelines = self.lines-3 self.w = curses.initscr() # fenetre hauteur largeur y x self.wheader = curses.newwin( 1, self.cols, 0, 0) self.wfile = curses.newwin(self.wfilelines, self.cols, 1, 0) self.wfooter = curses.newwin( 1, self.cols, self.lines-2, 0) self.wcmd = curses.newwin( 1, self.cols, self.lines-1, 0) curses.noecho() curses.cbreak() curses.nonl() # permet d'activer la touche enter (code 13) curses.curs_set(0) curses.mousemask(0) curses.mouseinterval(0) self.w.keypad(1) self.w.nodelay(0) self.w.timeout(self.timeout) try: self.initcolors_1() except: self.initcolors_2()
def __init__(self, term_stream=sys.stdout): try: import curses except: return if not term_stream.isatty(): return try: curses.setupterm() except: return self.COLS = curses.tigetnum('cols') self.LINES = curses.tigetnum('lines') for capability in self._STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(self, attrib, self._tigetstr(cap_name) or '') 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_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, curses.tparm(set_fg_ansi, 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 '') set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, 'BG_'+color, curses.tparm(set_bg_ansi, i) or '')
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_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for i, color in zip( range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, curses.tparm(set_fg_ansi, 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 '') set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: for i, color in zip( range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr( self, 'BG_' + color, curses.tparm( set_bg_ansi, i) or '')
def get_term_size(): """ Get the number of lines and columns of the tty that is connected to stdout. Returns a tuple of (lines, columns) or (-1, -1) if an error occurs. The curses module is used if available, otherwise the output of `stty size` is parsed. """ if not sys.stdout.isatty(): return -1, -1 try: import curses try: curses.setupterm() return curses.tigetnum('lines'), curses.tigetnum('cols') except curses.error: pass except ImportError: pass st, out = portage.subprocess_getstatusoutput('stty size') if st == os.EX_OK: out = out.split() if len(out) == 2: try: return int(out[0]), int(out[1]) except ValueError: pass return -1, -1
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: raise # guess false in case of error return False
def __init__(self, term_stream=sys.stdout): # 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 hasattr(term_stream, 'isatty') or 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._escape_code(self._tigetstr(cap_name))) # Colors set_fg = self._tigetstr('setf') if set_fg: if not isinstance(set_fg, bytes): set_fg = set_fg.encode('utf-8') for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, self._escape_code(curses.tparm((set_fg), i))) set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: if not isinstance(set_fg_ansi, bytes): set_fg_ansi = set_fg_ansi.encode('utf-8') for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, self._escape_code(curses.tparm((set_fg_ansi), i))) set_bg = self._tigetstr('setb') if set_bg: if not isinstance(set_bg, bytes): set_bg = set_bg.encode('utf-8') for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, 'BG_'+color, self._escape_code(curses.tparm((set_bg), i))) set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: if not isinstance(set_bg_ansi, bytes): set_bg_ansi = set_bg_ansi.encode('utf-8') for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, 'BG_'+color, self._escape_code(curses.tparm((set_bg_ansi), i)))
def get_real_termial_size(): try: size = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')) return size except: w = curses.tigetnum('cols') h = curses.tigetnum('lines') return (h, w)
def _init(): """ Initialize 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). """ def _tigetstr(cap_name): # String capabilities can include "delays" of the form "$<2>". # For any modern terminal, we should be able to just ignore # these, so strip them out. import curses cap = curses.tigetstr(cap_name) or '' return re.sub(r'\$<\d+>[/*]?', '', cap) _term_stream = sys.stdout # Curses isn't available on all platforms try: import curses except: sys.stderr.write("INFO: no curses support: you won't see colors\n") 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. colors.COLS = curses.tigetnum('cols') colors.LINES = curses.tigetnum('lines') # Look up string capabilities. for capability in _STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(colors, attrib, _tigetstr(cap_name) or '') # Colors set_fg = _tigetstr('setf') if set_fg: for i, color in zip(range(len(_COLORS)), _COLORS): setattr(colors, color, curses.tparm(set_fg, i) or '') set_fg_ansi = _tigetstr('setaf') if set_fg_ansi: for i, color in zip(range(len(_ANSICOLORS)), _ANSICOLORS): setattr(colors, color, curses.tparm(set_fg_ansi, i) or '') set_bg = _tigetstr('setb') if set_bg: for i, color in zip(range(len(_COLORS)), _COLORS): setattr(colors, 'BG_'+color, curses.tparm(set_bg, i) or '') set_bg_ansi = _tigetstr('setab') if set_bg_ansi: for i, color in zip(range(len(_ANSICOLORS)), _ANSICOLORS): setattr(colors, 'BG_'+color, curses.tparm(set_bg_ansi, i) or '')
def __init__(self, term_stream=sys.stdout, escape=False): """ 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). """ # when printing things out on lines accepting user input control # characters must be wrapped in special characters for correct # word wrapping, always wrap when escape == True self.escape = escape # 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_fg_ansi = self._tigetstr("setaf") if set_fg_ansi: for i, color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, curses.tparm(set_fg_ansi, 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 "") set_bg_ansi = self._tigetstr("setab") if set_bg_ansi: for i, color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, "BG_" + color, curses.tparm(set_bg_ansi, i) or "")
def __init__(self,pNames=''): Actor.__init__(self,pNames) try: import curses curses.setupterm() self.linebreak = curses.tigetnum('cols') self.lines = curses.tigetnum('lines') except: self.linebreak = 80 self.lines = 25
def start(): curses.setupterm() lines=curses.tigetnum('lines') cols=curses.tigetnum('cols') if int(lines)<22: print ' 窗口太小,请调整窗口高度' elif int(cols)<60: print ' 窗口太小,请调整窗口宽度' else: Menu().start()
def __curses(): """Try to discover terminal width with curses library.""" #noinspection PyBroadException try: import curses curses.setupterm() cr = (curses.tigetnum('cols'), curses.tigetnum('lines')) except Exception: return None return cr
def get_winsize(): try: import curses curses.setupterm() w = curses.tigetnum('cols') h = curses.tigetnum('lines') except: try: w = os.environ['COLS'] h = os.environ['LINES'] except: w = 80; h = 25 return w,h
def get_size(): try: h, w = int(os.environ['LINES']), int(os.environ['COLS']) except KeyError: try: h ,w = curses.tigetnum('lines'), curses.tigetnum('cols') except: try: s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s) h, w = struct.unpack('HHHH', x)[:2] except: h, w = 25, 80 return h, w
def __init__(self): curses.setupterm() #初始化终端 self.screen = curses.initscr() self.LINES=curses.tigetnum('lines') #终端行数 self.COLS=curses.tigetnum('cols') #列数 self.show_begin_line=int((int(self.LINES)-22)/2-1) # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
def __init__(self, term_stream=sys.stdout): # Curses isn't available on all platforms try: import curses except ImportError: 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() # pylint: disable=bare-except except: return # Look up numeric capabilities. TerminalController.COLS = curses.tigetnum('cols') TerminalController.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 b'') # Colors set_fg = self._tigetstr('setf') if set_fg: for i, color in zip(list(range(len(self._COLORS))), self._COLORS): setattr(self, color, curses.tparm(set_fg, i) or b'') set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for i, color in zip(list(range(len(self._ANSICOLORS))), self._ANSICOLORS): setattr(self, color, curses.tparm(set_fg_ansi, i) or b'') set_bg = self._tigetstr('setb') if set_bg: for i, color in zip(list(range(len(self._COLORS))), self._COLORS): setattr(self, 'BG_' + color, curses.tparm(set_bg, i) or b'') set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: for i, color in zip(list(range(len(self._ANSICOLORS))), self._ANSICOLORS): setattr( self, 'BG_' + color, curses.tparm(set_bg_ansi, i) or b'')
def __init__(self, setFancy=1): self.fancy = 1 self.effect = {} try: import sys,curses curses.setupterm() if not sys.stdout.isatty(): raise Exception() except: # if an exception is thrown we are !fancy self.fancy = 0 self.effect['cols'] = 80 self.effect['lines'] = 24 self.effect['cols'] = curses.tigetnum('cols') or 80 self.effect['lines'] = curses.tigetnum('lines') or 24 if(not (setFancy and self.fancy)): self.fancy = 0; return self.effect['clear'] = curses.tigetstr('clear') or '' self.effect['clear_bol'] = curses.tigetstr('el1') or '' self.effect['bol'] = curses.tigetstr('cl') or '' self.effect['up'] = curses.tigetstr('cuu1') or '' self.effect['hide_curs'] = curses.tigetstr('civis') or '' self.effect['show_curs'] = curses.tigetstr('cnorm') or '' self.effect['clear_eol'] = curses.tigetstr('el') or '' self.effect['reverse'] = curses.tigetstr('rev') or '' self.effect['bold'] = curses.tigetstr('bold') or '' self.effect['blink'] = curses.tigetstr('blink') or '' self.effect['normal'] = curses.tigetstr('sgr0') or '' self.effect['underline'] = curses.tigetstr('smul') or '' colors = "black;blue;green;cyan;red;magenta;yellow;white".split(";") set_fg = curses.tigetstr('setf') set_bg = curses.tigetstr('setb') if(set_fg): for i,key in enumerate(colors): self.effect["fg_"+key] = curses.tparm(set_fg, i) if(set_bg): for i,key in enumerate(colors): self.effect["bg_"+key] = curses.tparm(set_bg, i)
def __init__(self, stream = None): """ Construct this formatter. Provides colored output if the stream parameter is specified and is an acceptable TTY. We print hardwired escape sequences, which will probably break in some circumstances; for this unfortunate shortcoming, we apologize. """ # select and construct format string import curses format = None if stream and hasattr(stream, "isatty") and stream.isatty(): curses.setupterm() # FIXME do nice block formatting, increasing column sizes as necessary if curses.tigetnum("colors") > 2: format = \ "%s%%(asctime)s%s %%(message)s" % ( TTY_Formatter._NAME_COLOR, TTY_Formatter._COLOR_END, ) if format is None: format = "%(name)s - %(levelname)s - %(message)s" # initialize this formatter logging.Formatter.__init__(self, format, TTY_Formatter._DATE_FORMAT)
def report(self): curses.setupterm() cols = curses.tigetnum('cols') result = {} #result['Serious'] = 0 #result['High'] = 0 #result['Medium'] = 0 #result['Low'] = 0 print '-' * cols print '| {0} | {1} | {2} |'.format('LEVEL'.ljust(7), 'TYPE'.ljust(20), 'DETAIL'.ljust(cols - 37)) print '-' * cols rresult = [] acc = 1 for rule in self.results: print '| {0} | {1} | {2} |'.format(rule.severity.ljust(7), rule.type.ljust(20), rule.xurl[:cols - 37].ljust(cols - 37)) rresult.append({'type':rule.type, 'severity':rule.severity, 'payload':rule.url, 'acc':acc, 'description':rule.description, 'suggestion':rule.suggestion, 'file':rule.file}) acc = acc + 1 try: result[rule.severity] += 1 except: result[rule.severity] = 1 print '-' * cols for i in result: print result[i], i trender = {'site':self.urlroot, 'list':rresult} env = jinja2.Environment(loader = jinja2.PackageLoader('Scanner', '.')) template = env.get_template('report-template.html') f = open(self.output, 'w') #print trender f.write(template.render(trender).encode('utf8')) f.close() print 'Output: ', os.path.realpath(self.output)
def enable_pretty_logging(options=options): """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.FileHandler(options.log_file_prefix, 'w') # not append channel.setFormatter(_LogFormatter(color=False)) root_logger.addHandler(channel) if (options.log_to_stderr or (options.log_to_stderr is None and not root_logger.handlers)): # Set up color if we are in a tty and curses is installed color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except Exception: pass channel = logging.StreamHandler() channel.setFormatter(_LogFormatter(color=color)) root_logger.addHandler(channel)
def __init__(self,screen): self.screen =screen self.filename='' self.info='' self.lines=[] self.key=0 self.show_number=True self.line_no=0 self.col=0 self.offset=0 self.height=curses.tigetnum('lines') self.width = curses.tigetnum('cols') self.word=None self.mode='Command' self.mark=None self.running=True
def number_of_colors(self): """Return the number of colors the terminal supports. Common values are 0, 8, 16, 88, and 256. Though the underlying capability returns -1 when there is no color support, we return 0. This lets you test more Pythonically:: if term.number_of_colors: ... We also return 0 if the terminal won't tell us how many colors it supports, which I think is rare. """ # This is actually the only remotely useful numeric capability. We # don't name it after the underlying capability, because we deviate # slightly from its behavior, and we might someday wish to give direct # access to it. if not self._does_styling: return 0 colors = tigetnum('colors') # Returns -1 if no color support, -2 if no # such cap. # self.__dict__['colors'] = ret # Cache it. It's not changing. # (Doesn't work.) return colors if colors >= 0 else 0
def display_status_line(self, progress, module_num, message): if self.is_end_of_build: # hardcode progress to 100% at the end of the build progress = 1 columns = curses.tigetnum('cols') width = columns / 2 num_hashes = int(round(progress * width)) progress_bar = '[' + (num_hashes * '=') + ((width - num_hashes) * '-') + ']' module_no_digits = len(str(len(self.modulelist))) format_str = '%%%dd' % module_no_digits module_pos = '[' + format_str % module_num + '/' + format_str % len(self.modulelist) + ']' output = '%s %s %s%s%s' % (progress_bar, module_pos, t_bold, message, t_reset) text_width = len(output) - (len(t_bold) + len(t_reset)) if text_width > columns: output = output[:columns+len(t_bold)] + t_reset else: output += ' ' * (columns-text_width) sys.stdout.write('\r'+output) if self.is_end_of_build: sys.stdout.write('\n') sys.stdout.flush()
def terminal_width(self): """Return the terminal width if possible, otherwise return 0. """ ncols = 0 try: import curses 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 (ImportError, TypeError): pass return ncols
def enable_pretty_logging(): """Turns on formatted logging output as configured.""" 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: pass channel = logging.StreamHandler() channel.setFormatter(_LogFormatter(color=color)) root_logger.addHandler(channel)
def _stderr_supports_color(): try: if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): if curses: curses.setupterm() if curses.tigetnum("colors") > 0: return True elif colorama: if sys.stderr is getattr(colorama.initialise, 'wrapped_stderr', object()): return True except Exception: # Very broad exception handling because it's always better to # fall back to non-colored logs than to break at startup. pass return False
def stream_has_colours(stream): """ True if stream supports colours. Python cookbook, #475186 """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
def MyCallback(pct_complete, message): """ The callback function that gets status updates. Just prints a low-fi progress bar and reflects the status message passed in. Example: [###### ] Doing some thing... """ curses.setupterm() term_width = curses.tigetnum('cols') progress_bar = " [" + "".ljust(int(pct_complete * 10), '#') + "".ljust( 10 - int(pct_complete * 10), ' ') + "] " log_line = progress_bar + message sys.stdout.write(log_line.ljust(term_width) + '\r') sys.stdout.flush()
def get_color(self): """Return whether the system can use colors or not""" if sys.stdout.isatty(): try: import curses curses.setupterm() if curses.tigetnum('colors') < 0: return False except ImportError: sys.stderr.write('Color support is disabled as python-curses is not installed.') return False except: sys.stderr.write('Color support is disabled as curses does not find terminal "%s".' % os.getenv('TERM')) return False return True return False
def __init__(self, outs=sys.stdout, errs=sys.stderr, *args, **kwargs): Reporter.__init__(self, outs, errs, *args, **kwargs) self.count_result_lines = 0 self.count_status_lines = 0 self.count_log_lines = 0 # initialize curses import curses curses.setupterm() # required terminal capabilities self.CURSOR_UP = curses.tigetstr('cuu1') self.CURSOR_BOL = curses.tigetstr('cr') self.CURSOR_DOWN = curses.tigetstr('cud1') self.CLEAR_EOL = curses.tigetstr('el') self.NORMAL = curses.tigetstr('sgr0') self.COLUMNS = curses.tigetnum('cols') setf = curses.tigetstr('setf') setaf = curses.tigetstr('setaf') if setf: # self.COLOR_BLUE = curses.tparm(setf, 1) self.COLOR_GREEN = curses.tparm(setf, 2) self.COLOR_CYAN = curses.tparm(setf, 3) self.COLOR_RED = curses.tparm(setf, 4) self.COLOR_MANGENTA = curses.tparm(setf, 5) self.COLOR_YELLOW = curses.tparm(setf, 6) elif setaf: self.COLOR_RED = curses.tparm(setaf, 1) self.COLOR_GREEN = curses.tparm(setaf, 2) self.COLOR_YELLOW = curses.tparm(setaf, 3) # self.COLOR_BLUE = curses.tparm(setaf, 4) self.COLOR_MANGENTA = curses.tparm(setaf, 5) self.COLOR_CYAN = curses.tparm(setaf, 6) else: # self.COLOR_BLUE = "" self.COLOR_GREEN = "" self.COLOR_CYAN = "" self.COLOR_RED = "" self.COLOR_YELLOW = "" # the lines themselves, by test name self.lines = {} # test name to line position mapping for results and status self.resultLines = [] self.statusLines = []
def terminal_width(self): """Return the terminal width if possible, otherwise return 0. """ ncols = 0 try: import curses import io try: curses.setupterm() ncols = curses.tigetnum("cols") except AttributeError: # windows curses doesn't implement setupterm or tigetnum # code below from # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694 from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct ( bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy, ) = struct.unpack("hhhhHhhhhhh", csbi.raw) ncols = right - left + 1 except curses.error: pass except io.UnsupportedOperation: pass except (ImportError, TypeError): pass return ncols
def has_colors(fp): """Test if given file is an ANSI color enabled tty.""" # The is_tty() function ensures that we do not colorize # redirected streams, as this is almost never what we want if not is_tty(fp): return False if os.name == 'nt': return True elif has_curses: import curses try: curses.setupterm(os.environ.get("TERM"), fp.fileno()) # More than 8 colors are good enough. return curses.tigetnum("colors") >= 8 except curses.error: return False return False
def console_has_colours(stream): """ Detects if the specified stream has colourising capability. :param stream: stream to check (typically sys.stdout) """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
def __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('=') s = self._tigetstr(cap_name) or '' if isinstance(s, bytes): s = s.decode('utf-8') setattr(self, attrib, s) 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): s = curses.tparm(b(set_fg), i) or '' if isinstance(s, bytes): s = s.decode('utf-8') setattr(self, color, s) set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for i, color in enumerate(self._ANSICOLORS): s = curses.tparm(b(set_fg_ansi), i) or '' if isinstance(s, bytes): s = s.decode('utf-8') setattr(self, color, s)
def __init__(self, main, helper, console, errconsole, format): self.main = main self.helper = helper self.cuu = None self.stdinbackup = None self.interactive = sys.stdout.isatty() self.footer_present = False self.lastpids = [] if not self.interactive: return try: import curses except ImportError: sys.exit("FATAL: The knotty ui could not load the required curses python module.") import termios self.curses = curses self.termios = termios try: fd = sys.stdin.fileno() self.stdinbackup = termios.tcgetattr(fd) new = copy.deepcopy(self.stdinbackup) new[3] = new[3] & ~termios.ECHO termios.tcsetattr(fd, termios.TCSADRAIN, new) curses.setupterm() if curses.tigetnum("colors") > 2: format.enable_color() self.ed = curses.tigetstr("ed") if self.ed: self.cuu = curses.tigetstr("cuu") try: self._sigwinch_default = signal.getsignal(signal.SIGWINCH) signal.signal(signal.SIGWINCH, self.sigwinch_handle) except: pass self.rows, self.columns = self.getTerminalColumns() except: self.cuu = None if not self.cuu: self.interactive = False bb.note("Unable to use interactive mode for this terminal, using fallback") return console.addFilter(InteractConsoleLogFilter(self, format)) errconsole.addFilter(InteractConsoleLogFilter(self, format))
def __init__(self, rootpath, threadcount): self.rootpath = rootpath self.threadcount = threadcount curses.setupterm() #lines = curses.tigetnum('lines') self.cols = curses.tigetnum('cols') if self.check() == False: return self.updatestatus('Initializing......') self.pool = threadpool.ThreadPool(threadcount) urls = [] exts = ['rar', 'htm', 'html', 'xhtml', 'zip', 'js'] for url in open('list.dic'): for ext in exts: urls.append(url.strip() + '.' + ext) self.reqs = threadpool.makeRequests(self.detect, urls) self.run()
def get(cap, *args, **kwargs): """ Get a terminal capability exposes through the `curses` module. """ # Hack for readthedocs.org if "READTHEDOCS" in os.environ: return "" if _win_compat != None: ret = _win_compat.get(cap).get(args) return ret if kwargs != {}: raise TypeError("get(): No such argument %r" % kwargs.popitem()[0]) if _cache == {}: # Fix for BPython try: curses.setupterm() except: pass s = _cache.get(cap) if not s: s = curses.tigetstr(cap) if s == None: s = curses.tigetnum(cap) if s == -2: s = curses.tigetflag(cap) if s == -1: # default to empty string so tparm doesn't fail s = "" else: s = bool(s) _cache[cap] = s # if 's' is not set 'curses.tparm' will throw an error if given arguments if args and s: r = curses.tparm(s, *args) return r.decode("utf-8") else: if isinstance(s, bytes): return s.decode("utf-8") else: return s
def _color(lvl): try: import curses except ImportError: curses = None color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except: pass if not color: return u_(''), u_('') # 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 = u_(fg_color, "ascii") colors_map = { logging.DEBUG: u_( curses.tparm(fg_color, 4), # Blue "ascii"), logging.INFO: u_( curses.tparm(fg_color, 2), # Green "ascii"), logging.WARNING: u_( curses.tparm(fg_color, 3), # Yellow "ascii"), logging.ERROR: u_( curses.tparm(fg_color, 1), # Red "ascii"), 'grey': u_( curses.tparm(fg_color, 0), # Grey "ascii"), } _normal = u_(curses.tigetstr("sgr0"), "ascii") return colors_map.get(lvl, _normal), _normal
def block_progress_bar(percentage): global PROGRESS_BLOCKED lines = curses.tigetnum("lines") # Save cursor __print_control_code(CODE_SAVE_CURSOR) # Move cursor position to last row __print_control_code("\033[" + str(lines) + ";0f") # Clear progress bar __tput("el") # Draw progress bar PROGRESS_BLOCKED = True __print_bar_text(percentage) # Restore cursor position __print_control_code(CODE_RESTORE_CURSOR)
def max_colors(): """Max colors current terminal supports. :returns: Integer. For instance, for 'xterm' it is usually 256 .. note:: Uses :mod:`curses` """ global _COLORS if _COLORS is None: import curses try: curses.setupterm() _COLORS = curses.tigetnum('colors') except (OSError, curses.error): _COLORS = 1 return _COLORS
def printColor(text, colour=WHITE): has_colours = True if not hasattr(sys.stdout, "isatty"): has_colours = False if not sys.stdout.isatty(): has_colours = False # auto color only on TTYs try: import curses curses.setupterm() has_colours = (curses.tigetnum("colors") > 2) except: # guess false in case of error has_colours = False if has_colours: seq = "\x1b[1;%dm" % (30 + colour) + text + "\x1b[0m\n" sys.stdout.write(seq) else: sys.stdout.write(text)
def supported(self): """ A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ # assuming stderr # isatty() returns False when SSHd into Win32 machine if 'CYGWIN' in os.environ: return True if not sys.stderr.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
def draw_progress_bar(percentage, context="", delay=None): lines = curses.tigetnum("lines") # Save cursor __print_control_code(CODE_SAVE_CURSOR) # Move cursor position to last row __print_control_code("\033[" + str(lines) + ";0f") # Clear progress bar __tput("el") # Draw progress bar __print_bar_text(percentage, context) # Restore cursor position __print_control_code(CODE_RESTORE_CURSOR) if delay: time.sleep(delay)
def enable_pretty_logging(logger, level='info'): """Turns on formatted logging output as configured. """ logger.setLevel(getattr(logging, level.upper())) if not logger.handlers: # Set up color if we are in a tty and curses is installed color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except: pass channel = logging.StreamHandler() channel.setFormatter(_LogFormatter(color=color)) logger.addHandler(channel)
def __has_colors(stream): """ Is tty output check :param object stream: input stream :return: bool """ 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 Exception: # guess false in case of error return False
def __init__(self, fmt=None, datefmt=None, width=None): """Constructor. See the Python standard library reference for a documentation of fmt and datefmt. width is the maximum width of the generated text blocks. """ logging.Formatter.__init__(self, fmt, datefmt) if None == width: try: import curses curses.setupterm() self._width = curses.tigetnum('cols') # Leave a border of two blanks to prevent that full lines # wrap to the next line self._width -= 2 except: self._width = 70 # default to 70
def _color_supported(stream, force=False): """Return the number of supported colors""" min_colors = 8 if force else 0 if sys.platform == 'win32' and 'ANSICON' not in os.environ: return min_colors if hasattr(stream, 'isatty') and stream.isatty(): # we have a tty try: import curses curses.setupterm() return max(min_colors, curses.tigetnum('colors')) except Exception: # not picky. pass if force: p = subprocess.Popen(['tput', 'colors'], stdout=subprocess.PIPE) return max(min_colors, int(p.communicate()[0])) return 0
def __init__(self, terminalreporter, *, rewrite=False): super().__init__(terminalreporter, rewrite=rewrite) try: import curses default_scheme = 'dark' curses.setupterm() if curses.tigetnum("colors") >= 256: default_scheme = 'dark-256color' except ModuleNotFoundError: default_scheme = 'dark-256color' scheme = os.environ.get('LG_COLOR_SCHEME', default_scheme) if scheme not in ColoredStepReporter.EVENT_COLOR_SCHEMES.keys(): logging.warning("Color scheme '%s' unknown", scheme) scheme = default_scheme self.color_scheme = ColoredStepReporter.EVENT_COLOR_SCHEMES[scheme]
def select_formatter(): """Heuristically choose the best formatter. It may not be correct in all cases; this is for simple applications such as a bot. If Curses is found, it will check if stdout is a terminal. If it isn't, :py:class:`~PyIRC.formatting.formatters.NullFormatter` is chosen. If it is, the number of colours the terminal supports is probed, which determines which formatter will be used. If the platform is Windows, the :py:class:`~PyIRC.formatting.formatters.ANSIFormatter` will be chosen. If your environment supports ≥ 256 colours, set the environmental variable ``TRUECOLOUR`` or ``TRUECOLOR`` to any value but 0 to try full-colour support using the :py:class:`~PyIRC.formatting.formatters.XTermTrueColourFormatter``. """ if curses is not None: if hasattr(os, "isatty") and not os.isatty(sys.stdout.fileno()): # Probably best not to dump formatting into logs return NullFormatter curses.setupterm() colors = curses.tigetnum("colors") if colors >= 256: t = os.environ.get("TRUECOLOR", os.environ.get("TRUECOLOUR"), False) if t and t != '0': return XTermTrueColourFormatter return XTerm256ColourFormatter elif colours >= 16: return XTerm16ColourFormatter # Better than nothing... return ANSIFormatter else: if sys.platform.startswith("win32"): # XXX differentiate stdout from a file return ANSIFormatter return NullFormatter
def add_console_logger(logger, level='info'): """ 增加console作为日志输入. """ 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 console = logging.StreamHandler() console.setFormatter(_LogFormatter(color=color)) logger.addHandler(console)
def report(self): curses.setupterm() cols = curses.tigetnum('cols') result = {} #result['Serious'] = 0 #result['High'] = 0 #result['Medium'] = 0 #result['Low'] = 0 print '-' * cols print '| {0} | {1} | {2} |'.format('LEVEL'.ljust(7), 'TYPE'.ljust(20), 'DETAIL'.ljust(cols - 37)) print '-' * cols rresult = [] acc = 1 for rule in self.results: print '| {0} | {1} | {2} |'.format( rule.severity.ljust(7), rule.type.ljust(20), rule.xurl[:cols - 37].ljust(cols - 37)) rresult.append({ 'type': rule.type, 'severity': rule.severity, 'payload': rule.url, 'acc': acc, 'description': rule.description, 'suggestion': rule.suggestion, 'file': rule.file }) acc = acc + 1 try: result[rule.severity] += 1 except: result[rule.severity] = 1 print '-' * cols for i in result: print result[i], i trender = {'site': self.urlroot, 'list': rresult} env = jinja2.Environment(loader=jinja2.PackageLoader('Scanner', '.')) template = env.get_template('report-template.html') f = open(self.output, 'w') #print trender f.write(template.render(trender).encode('utf8')) f.close() print 'Output: ', os.path.realpath(self.output)
def enable_pretty_logging(level=logging.DEBUG): logger = logging.getLogger() h = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s:%(levelname)-7s:%(name)-12s:%(message)s') try: import curses color = False curses.setupterm() if curses.tigetnum("colors") > 0: color = True formatter = TornadoLogFormatter(color=color) except: import traceback traceback.print_exc() finally: h.setLevel(level) h.setFormatter(formatter) logger.setLevel(level) logger.addHandler(h)
def downloads_changed(self): import gobject if self.monitored_downloads and self.update is None: if self.screen_width is None: try: import curses curses.setupterm() self.screen_width = curses.tigetnum('cols') or 80 except Exception as ex: info("Failed to initialise curses library: %s", ex) self.screen_width = 80 self.show_progress() self.update = gobject.timeout_add(200, self.show_progress) elif len(self.monitored_downloads) == 0: if self.update: gobject.source_remove(self.update) self.update = None print self.last_msg_len = None
def count_ansi_colors(term_name=None): """Counts ANSI-coded colors a terminal supports. Bug: Subsequent calls might return the same value as the first if terminfo has to be used that is when term_info is not in 'xterm-256colors', 'xterm', 'unknown'. Args: term_name (str): A string like 'xterm' or 'unknown', defaults to the environment value for TERM. Returns: int: Number of ANSI-coded colors the terminal supports. """ if term_name is None: term_name = os.getenv('TERM') # We hardcode a few values as curses does not reload terminfo on subsequent # calls to setupterm and terminfo often is mis-installed. if term_name.endswith('-256color'): return 256 if term_name.endswith('-16color'): return 16 elif term_name in ['xterm', 'hterm', 'screen']: return 8 elif term_name == 'unknown': return 0 try: # We have to provide a temporary file as the fd to prevent ncurses from # messing with the terminal. with tempfile.NamedTemporaryFile() as f: curses.setupterm(term_name, f.fileno()) for capability in ('setaf', 'setab', 'bold'): if not curses.tigetstr(capability): # If we get here it means the terminal support colors but not # through ANSI color sequences. return 0 except curses.error: return 0 return curses.tigetnum("colors")
def _stderr_supports_color(): # Colors can be forced with an env variable if os.getenv('LOGZERO_FORCE_COLOR') == '1': return True # Windows supports colors with colorama if os.name == 'nt': return True # Detect color support of stderr with curses (Linux/macOS) if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: return True except Exception: pass return False