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
python类error()的实例源码
colorizer.py 文件源码
项目:Trusted-Platform-Module-nova
作者: BU-NU-CLOUD-SP16
项目源码
文件源码
阅读 20
收藏 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 文件源码
项目:Trusted-Platform-Module-nova
作者: BU-NU-CLOUD-SP16
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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 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