我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.error()。
def _insert_printable_char(self, ch): (y, x) = self.win.getyx() if y < self.maxy or x < self.maxx: if self.insert_mode: oldch = self.win.inch() # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the window. try: self.win.addch(ch) except curses.error: pass if self.insert_mode: (backy, backx) = self.win.getyx() if curses.ascii.isprint(oldch): self._insert_printable_char(oldch) self.win.move(backy, backx)
def _insert_printable_char(self, ch): (y, x) = self.win.getyx() if y < self.maxy or x < self.maxx: # Possible reference before assignment fix oldch = None if self.insert_mode: oldch = self.win.inch() # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the window. try: self.win.addch(ch) except curses.error: pass if self.insert_mode: (backy, backx) = self.win.getyx() if curses.ascii.isprint(oldch): self._insert_printable_char(oldch) self.win.move(backy, backx)
def put(self, x, y, text, fg, bg): """ Puts a string at the desired coordinates using the provided colors. :param x: X position :param y: Y position :param text: Text to write :param fg: Foreground color number :param bg: Background color number """ self.mutex.acquire() if x < self.width and y < self.height: try: self.screen.addstr(int(y), int(x), symbols.encode(text), self.pairs[fg, bg]) except curses.error: # Ignore out of bounds error pass self.mutex.release()
def _start_ui(self, stdscr): """TODO docs""" rogue_height = 26 rogue_width = 84 # using a pad instead of the default win, it's safer self.stdscr = curses.newpad(rogue_height, rogue_width) self.stdscr.nodelay(True) curses.curs_set(False) self.draw_from_rogue() minlogsize = 4 if curses.LINES - 1 >= rogue_height + minlogsize: # there's enough space to show the logs self.logpad = curses.newpad(curses.LINES - 1, curses.COLS - 1) while True: if self.timer_callback: self.timer_callback() time.sleep(self.sleep_time) if self.keypress_callback: try: key = self.stdscr.getkey() event = Event() event.char = key self.keypress_callback(event) except curses.error: pass
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
def supported(cls, stream=sys.stdout): try: import win32console screenBuffer = win32console.GetStdHandle( win32console.STD_OUT_HANDLE) except ImportError: return False import pywintypes try: screenBuffer.SetConsoleTextAttribute( win32console.FOREGROUND_RED | win32console.FOREGROUND_GREEN | win32console.FOREGROUND_BLUE) except pywintypes.error: return False else: return True
def deposit(): printMsg("Loading bitcoin address...") # connect to node and get new wallet address try: addr = rpc_connection.getnewaddress() except (socket.error, httplib.CannotSendRequest): printMsg("getnewaddress http error", COLOR_RED) time.sleep(2) return False # show off the new address! printMsg(addr, COLOR_GREEN, 1) showQR(addr, 'M') # called by withdraw() to display segment of a list as a menu
def showQR(addr, errcorr): # generate QR code and display on LED grid code = pyqrcode.create(addr, error=errcorr, version=3) t = code.text(1) row = 31 col = 0 bufferInit() for i in t: if i != '\n': bufferPixel(row, col, 255-int(i)*255, 255-int(i)*255, 255-int(i)*255) col += 1 else: row -= 1 col = 0 bufferDraw() #time.sleep(0.001) # give us a chance to scan it time.sleep(QRTIME) # draw blocks since last difficulty adjustment
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
def __init__(self, stream, charset=None): # our Enterprise logic follows self.stream_isatty = stream.isatty() if charset is None: charset = ENTERPRISE_CHARSET if self.stream_isatty else '.' super(QubesSpinnerEnterpriseEdition, self).__init__(stream, charset) if self.stream_isatty: try: curses.setupterm() self.has_terminfo = True self.cub1 = curses.tigetstr('cub1').decode() except (curses.error, io.UnsupportedOperation): # we are in very non-Enterprise environment self.has_terminfo = False else: self.cub1 = ''
def 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
def _printResults(self, flavor, errors, formatter): """ Print a group of errors to the stream. @param flavor: A string indicating the kind of error (e.g. 'TODO'). @param errors: A list of errors, often L{failure.Failure}s, but sometimes 'todo' errors. @param formatter: A callable that knows how to format the errors. """ for reason, cases in self._groupResults(errors, formatter): self._writeln(self._doubleSeparator) self._writeln(flavor) self._write(reason) self._writeln('') for case in cases: self._writeln(case.id())
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
def print_line(line, highlight=False): """A thin wrapper around curses's addstr().""" global lineno try: if highlight: line += " " * (win.getmaxyx()[1] - len(line)) win.addstr(lineno, 0, line, curses.A_REVERSE) else: win.addstr(lineno, 0, line, 0) except curses.error: lineno = 0 win.refresh() raise else: lineno += 1 # --- curses stuff
def print_line(line, highlight=False): """A thin wrapper around curses's addstr().""" global lineno try: if highlight: line += " " * (win.getmaxyx()[1] - len(line)) win.addstr(lineno, 0, line, curses.A_REVERSE) else: win.addstr(lineno, 0, line, 0) except curses.error: lineno = 0 win.refresh() raise else: lineno += 1 # --- /curses stuff
def refresh_window(procs, disks_read, disks_write): """Print results on screen by using curses.""" curses.endwin() templ = "%-5s %-7s %11s %11s %s" win.erase() disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \ % (bytes2human(disks_read), bytes2human(disks_write)) print_line(disks_tot) header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND") print_line(header, highlight=True) for p in procs: line = templ % ( p.pid, p._username[:7], bytes2human(p._read_per_sec), bytes2human(p._write_per_sec), p._cmdline) try: print_line(line) except curses.error: break win.refresh()
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
def dotheui(stdscr, args): ''' Here we springboard into the various bits of user interface. ''' color_err = ''' This terminal doesn't support color, so we cannot start the game. You can try to force this by changing the environment variable named `TERM` to be a string that tells Curses that this terminal supports colors. One way to do this would be to enter the following string on your terminal: TERM=xterm-256color After you've set this environment variable, try to launch DefuseDivision as you normally would. Some characters may display incorrectly, or look odd, but hopefully you'll be able to play :) ''' if not curses.has_colors(): return color_err if args.host is None: try: uiopts = mainmenu.mainmenu(stdscr) except KeyboardInterrupt: return "" except curses.error as err: if 'init_pair()' in str(err): return color_err else: raise err else: uiopts = {'mode': 'Multiplayer'} uiopts['connection'] = dict() uiopts['connection']['hostname'] = args.host port = args.port if port is None: port = 44444 uiopts['connection']['port'] = port client = instance_setup.create_client(stdscr, args, uiopts) stdscr.clear() return tc.main(stdscr, client, args)
def __init__(self, this_plant, this_data): '''Initialization''' self.initialized = False self.screen = curses.initscr() curses.noecho() curses.raw() curses.start_color() try: curses.curs_set(0) except curses.error: # Not all terminals support this functionality. # When the error is ignored the screen will look a little uglier, but that's not terrible # So in order to keep botany as accesible as possible to everyone, it should be safe to ignore the error. pass self.screen.keypad(1) self.plant = this_plant self.user_data = this_data self.plant_string = self.plant.parse_plant() self.plant_ticks = str(self.plant.ticks) self.exit = False self.infotoggle = 0 self.maxy, self.maxx = self.screen.getmaxyx() # Highlighted and Normal line definitions self.define_colors() self.highlighted = curses.color_pair(1) self.normal = curses.A_NORMAL # Threaded screen update for live changes screen_thread = threading.Thread(target=self.update_plant_live, args=()) screen_thread.daemon = True screen_thread.start() self.screen.clear() self.show(["water","look","garden","instructions"], title=' botany ', subtitle='options')
def draw(self, win): h, w = win.getmaxyx() win.bkgdset(' ', self.skycolor) # Draw Particles parttype = self.conf['particles_type'] for part in self.particles: part[0] = part[0]%w part[1] = part[1]%h try: if(parttype == 'Snow'): if(part[2] > 60): win.addstr(int(part[1]), int(part[0]), '?') else: win.addstr(int(part[1]), int(part[0]), '·') elif(parttype == 'Rain'): win.addstr(int(part[1]), int(part[0]), '|', curses.color_pair(2)) elif(parttype == 'Stars'): if(randint(0, 200) == 0): if(part[2] > 60): win.addstr(int(part[1]), int(part[0]), '?') else: win.addstr(int(part[1]), int(part[0]), '?') else: if(part[2] > 60): win.addstr(int(part[1]), int(part[0]), '?') elif(part[2] > 40): win.addstr(int(part[1]), int(part[0]), '·') else: win.addstr(int(part[1]), int(part[0]), '?') except curses.error: pass # Draw Ground try: for x, col in enumerate(self.ground): for y, cell in enumerate(col): if(cell): win.addstr(y, x, self.groundchars[x][y], self.groundcolor) except curses.error: # The very last character will error so except only once pass
def draw(self, win): h, w =win.getmaxyx() if(self.pos.y < 0): c = '^' elif(self.pos.x < 0): c = '<' elif(self.pos.x > w): c = '>' else: c = self.char display = self.pos.clamp(0, w-1, 0, h-1).int() if(self.age>3): try: if(self.pos.in_box(0, w, 0, h)): for i,tup in enumerate(self.tail): next = (self.tail + [(display.y, display.x)])[i+1] dif_y = -1 if (next[0] < tup[0]) else (1 if (next[0] > tup[0]) else 0) dif_x = -1 if (next[1] < tup[1]) else (1 if (next[1] > tup[1]) else 0) d = lines()[(dif_y, dif_x)] win.addstr(tup[0], tup[1], choice(['?','?',d, d])) win.addstr(display.y, display.x, c) except curses.error: pass self.tail += [(display.y, display.x)] if(len(self.tail) > self.conf['shot_tail']): self.tail = self.tail[1:]
def draw(self, win): for p in self.laser_points: try: win.addch(p.y, p.x, ['?', '?', '?', '?', ' '][int(self.age/5)], curses.color_pair(self.owner.colors)) except curses.error: pass
def draw(self, win): h, w = win.getmaxyx() for i in range(self.age): for theta in range(0, 360, 1+int(10/(i+1))): display = (self.pos + (cos(radians(theta)) * i, -sin(radians(theta)) * i)).int() if(display.in_box(0, w, 0, h)): self.world.destroy_ground(display.x, display.y) try: win.addstr(display.y, display.x, '#') except curses.error: pass
def __init__(self, arena_size): self.arena_size = arena_size self.max_moves = int(25*(2*arena_size*COLORS)/(28*6)) self.screen = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() try: curses.curs_set(False) except curses.error: pass self.screen.nodelay(True) self.window_size = self.screen.getmaxyx() if self.window_size[0] < self.arena_size+4 or self.window_size[1] < self.arena_size*2: print('Your screen is too short!') exit() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_CYAN) curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA) curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_YELLOW) curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_WHITE) self.offset_x = int((self.window_size[1]-2*self.arena_size)/2) self.offset_y = int((self.window_size[0]-self.arena_size)/2) self.moves_position=[ self.offset_y+self.arena_size+1, self.offset_x+self.arena_size-5 ] self.arena_initialize() self.screen.addstr( self.offset_y-2, self.offset_x, self.title, curses.color_pair(0)) self.screen.addstr( self.offset_y-2, self.offset_x+2*self.arena_size-17, "Press '?' to help", curses.color_pair(0))
def refresh_screen(self): for y in range(self.arena_size): for x in range(self.arena_size): try: self.screen.addstr( self.offset_y + y, self.offset_x + x*2, " ", curses.color_pair( self.arena[y][x] )) except curses.error: pass self.screen.addstr( self.moves_position[0], self.moves_position[1], "Moves {}/{} ".format(self.moves,self.max_moves), curses.color_pair(0)) self.screen.refresh()
def updatesourceinfo(win,iws,c): """ writes current state to info window :param win: the info window :param iws: the info window output dict should at minimum the keys 'dev','Driver','Mode','MAC','Manuf','Connected', :param c: the current config should be in the form config = {'SSID':None, 'dev':None, 'connect':None} """ # set defaults then check the conf dict for a device dev = c['dev'] if c['dev'] else '-'*_DEVLEN_ driver = mode = manuf = '-'*_FIXLEN_ hwaddr = '-'*_MACLEN_ conn = '-' color = CPS[WHITE] if c['dev']: try: card = pyw.getcard(dev) ifinfo = pyw.ifinfo(card) driver = ifinfo['driver'][:_FIXLEN_] # trim excess hwaddr = ifinfo['hwaddr'].upper() manuf = ifinfo['manufacturer'][:_FIXLEN_] # trim excess mode = pyw.modeget(card) conn = 'Y' if pyw.isconnected(card) else 'N' color = CPS[GREEN] except pyric.error as _e: raise error("ERRNO {0}. {1}".format(_e.errno,_e.strerror)) win.addstr(iws['dev'][0],iws['dev'][1],dev,color) win.addstr(iws['Driver'][0],iws['Driver'][1],driver,color) win.addstr(iws['Mode'][0],iws['Mode'][1],mode,color) win.addstr(iws['MAC'][0],iws['MAC'][1],hwaddr,color) win.addstr(iws['Manuf'][0],iws['Manuf'][1],manuf,color) win.addstr(iws['Connected'][0],iws['Connected'][1],conn,color)
def addstr(self, y, x, string, attr): try: self.window.addstr(y, x, string, attr) except curses.error: # Curses will error on the last line even when it works. # https://stackoverflow.com/questions/7063128/last-character-of-a-window-in-python-curses if y == self.max_y - 1: pass else: raise
def poll(self): while self.ts.run: while self.ts.pause: time.sleep(.1) bytes_polled = self.injector.process.stdout.readinto(self.T.r) if bytes_polled == sizeof(self.T.r): self.T.ic = self.T.ic + 1 error = False if self.T.r.valid: if self.search_unk and not self.T.r.disas_known and self.T.r.signum != self.SIGILL: error = True if self.search_len and self.T.r.disas_known and self.T.r.disas_length != self.T.r.length: error = True if self.search_dis and self.T.r.disas_known \ and self.T.r.disas_length != self.T.r.length and self.T.r.signum != self.SIGILL: error = True if self.search_ill and self.T.r.disas_known and self.T.r.signum == self.SIGILL: error = True if error: insn = cstr2py(self.T.r.raw_insn)[:self.T.r.length] r = copy.deepcopy(self.T.r) self.T.al.appendleft(r) if insn not in self.T.ad: if not self.low_mem: self.T.ad[insn] = r self.T.ac = self.T.ac + 1 if self.sync: with open(SYNC, "a") as f: f.write(result_string(insn, self.T.r)) else: if self.injector.process.poll() is not None: self.ts.run = False break
def draw_thing(self, thing, x_offset,y_offset): try: self.map_view.addch(thing.y-y_offset, thing.x-x_offset, thing.disp, curses.color_pair(self.color_palette[thing.color])) except curses.error: pass
def renderSky(screen, sky): screen.clear() try: for i in sky: for x in i: screen.addstr(x[0]) screen.addstr("\n") except curses.error: pass screen.refresh()
def keypress(screen): key = None try: key = screen.getkey() except curses.error as e: pass # raised if no key event is buffered # (because that's elegant... hmm) return key
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 test_menu_textpad_mod_rectangle_exception(self): """Test that curses.error is not raised when drawing outside the bounds of the window.""" def test_function(stdscr): stdscr.clear() stdscr = curses.initscr() ec2rlcore.menu_textpad_mod.rectangle(stdscr, curses.LINES + 1, curses.COLS + 1, 0, 0) curses.wrapper(test_function)
def rectangle(win, uly, ulx, lry, lrx): """ Draw a rectangle with corners at the provided upper-left and lower-right coordinates. Parameters: win (WindowObject): the screen/window uly (int): upper left y coordinate ulx (int): upper left x coordinate lry (int): lower right y coordinate lrx (int): lower right x coordinate Returns: None """ # Add exception handling try: win.vline(uly + 1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx + 1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx + 1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly + 1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER) # Catch attempts to print a character out of the bounds of the window except curses.error: pass