def __init__(self, file):
self.file = file
self.scr = curses.initscr()
self.scr.border()
self.scr_height, self.scr_width = self.scr.getmaxyx()
self.text_win = curses.newwin(self.scr_height - 1, self.scr_width, 1, 0)
self.file_text = file.content
if self.file_text != None:
self.text_win.addstr(self.file_text)
curses.noecho()
#curses.start_color()
#curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
if self.file.exists:
self.start_editor()
else:
curses.endwin()
gc.error('An error occurred while editing this file.')
python类endwin()的实例源码
def start_editor(self):
try:
# draw the top bar
top_bar = 'Editing ' + self.file.name + ' [press Ctrl+G to save and close]'
i = len(top_bar)
while i < self.scr_width:
top_bar += ' '
i += 1
self.scr.addstr(0, 0, top_bar, curses.A_REVERSE)
self.scr.refresh()
# let the user edit th efile
box = Textbox(self.text_win)
box.edit()
# get the file contents
self.file_text = box.gather()
finally:
# return to the game
curses.endwin()
gc.clear()
self.file.content = self.file_text
def gmode(self):
"""
Types automatically
"""
try:
fileptr = 0
while (fileptr + self.n) < len(self.file):
text = self.get_text(fileptr)
fileptr += self.n
self.stdscr.addstr(text)
self.stdscr.refresh()
sleep(0.1)
curses.endwin()
except KeyboardInterrupt:
curses.endwin()
exit()
def main():
game = Game(16)
while True:
game.refresh_screen()
new_color = game.get_key()
if new_color > 0 and new_color <= COLORS and game.status!='win':
old_color = game.arena[0][0]
if new_color != old_color:
game.moves+=1
game.paint( [0,0], old_color, new_color)
elif new_color==-2:
break
elif new_color==-1:
game.display_help()
game.screen.keypad(False)
curses.nocbreak()
curses.echo()
curses.endwin()
print('Thanks for playing!')
exit()
def main():
try:
screen = curses.initscr()
size = screen.getmaxyx()
sky = generateSky(size[0]-1, size[1]-1, 0.025)
while True:
if size[0] != screen.getmaxyx()[0] and size[1] != screen.getmaxyx()[1]:
size = screen.getmaxyx()
sky = generateSky(size[0]-1, size[1]-1, 0.05)
animateSky(sky)
renderSky(screen, sky)
time.sleep(1)
curses.endwin()
except KeyboardInterrupt:
curses.endwin()
except:
curses.endwin()
traceback.print_exc()
def run(self):
while any(_.is_alive() for _ in self.processes):
time.sleep(0.1)
self.stdscr_size = self.stdscr.getmaxyx()
self.build_progress_screen()
self.build_status_screen()
self.build_output_screen()
# terminate manually when all tasks finished
if self.task_num == self.task_total:
for _ in self.processes:
_.terminate()
self.stdscr.addstr(self.stdscr_size[0] - 2, 0,
'Done! please type "q" to exit.')
self.stdscr.refresh()
while self.stdscr.getch() != ord('q'):
time.sleep(1)
curses.endwin()
def draw(self, opt):
# Clear screen and draw default border:
self.screen.clear()
self.screen.border(0)
self.screen.addstr(10, 30, 'Hello world!') # Row 10, col 30
self.screen.addstr(11, 30, '[q] Quit') # Row 10, col 30
# self.screen.addstr(12, 30, '[{} ] Forward'.format(u'\u21E7'.encode('utf-8'))) # Row 10, row 30
# self.screen.addstr(20, 30, 'key {}'.format(opt))
# self.screen.addstr(13, 30, '[{} ] Reverse'.format(u'\u21E9'.encode('utf-8')))
# self.screen.addstr(14, 30, '[{} ] Left'.format(u'\u21E6'.encode('utf-8')))
# self.screen.addstr(15, 30, '[{} ] Right'.format(u'\u21E8'.encode('utf-8')))
self.screen.refresh() # Redraw screen.
# for key in self.windows:
# self.windows(key).refresh()
self.windows['commands'].refresh()
self.dummy += 0.1
self.windows['light'].refresh([self.dummy,-2.2222,3333,-4444.44444])
# win.refresh()
# opt = screen.getch() # Wait for user to enter character.
# curses.endwin() # End screen (ready to draw new one, but instead we exit)
time.sleep(0.1)
def init():
height_term, width_term = get_terminal_size()
height_min = COL_HEIGHT * HEIGHT + 2 + 9
width_min = COL_WIDTH * WIDTH + 2 + 5
if height_term < height_min or width_term < width_min:
# resize the terminal to fit the minimum size to display the connect4 before exit
stdout.write("\x1b[8;{h};{w}t".format(h=max(height_min, height_term), w=max(width_min, width_term)))
exit('\033[91m' + 'The terminal was too small, you can now restart ' + '\033[1m' + 'Connect4' + '\033[0m')
stdscr = curses.initscr()
height,width = stdscr.getmaxyx()
if height < height_min or width < width_min:
# abort the program if the terminal can't be resized
curses.endwin()
exit('Please resize your terminal [%d%s%d] (minimum required %d%s%d)' %(width, 'x', height, width_min, 'x', height_min))
curses.noecho()
curses.cbreak()
curses.curs_set(0)
stdscr.keypad(1)
#define the different colors
if curses.can_change_color():
defineColors()
#return stdscr, width
stdscr.clear()
stdscr.border(0)
return stdscr, width, height
def top(args):
scr = curses.initscr()
#scr.start_color()
curses.noecho()
curses.cbreak()
hx, wm = scr.getmaxyx()
scr.keypad(True)
try:
header = curses.newwin(HEADER_SIZE, wm, 0, 0)
body = curses.newwin(BODY_SIZE, wm, HEADER_SIZE, 0)
while True:
draw_header(header)
draw_body(body)
draw_footer(scr)
sleep(0.2)
except KeyboardInterrupt:
curses.nocbreak()
scr.keypad(False)
curses.echo()
curses.endwin()
def goodbye(self, msg=''):
"""
Exit gpymusic.
Arguements:
msg='': Message to display prior to exiting.
"""
if not self.curses:
if not self.test:
print(msg)
sys.exit()
self.addstr(self.outbar, msg)
common.mc.logout()
try:
common.client.mm.logout()
except:
pass
sleep(2)
crs.curs_set(1)
crs.endwin()
sys.exit()
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 leave(self):
'''Leave curses mode.'''
curses.nocbreak()
curses.echo()
self.window.keypad(False)
try:
curses.curs_set(self.old_cursor)
except:
pass
curses.endwin()
def __init__(self, file, n, godmode):
"""
main is the wrapper window
There are two nested windows, namely header and stdscr.
"""
self.main = curses.initscr()
self.ROWS, self.COLS = self.main.getmaxyx()
self.header = self.main.subwin(2, self.COLS, 0, 0)
# center the text
# cast it to int for python3 support
center = int((self.COLS / 2) - (len(HEADER) / 2))
self.header.addstr(center * ' ' + HEADER)
self.header.refresh()
self.stdscr = self.main.subwin(self.ROWS-1, self.COLS, 1, 0)
self.stdscr.idlok(True)
self.stdscr.scrollok(True)
curses.cbreak()
curses.noecho()
self.stdscr.keypad(1)
self.stdscr.refresh()
self.file = file
# this is for handling the backspaces
self.virtualfile = file.split('\n')
self.godmode = godmode
self.n = n
# handle terminal size
if self.COLS < 100:
curses.endwin()
print ('Error: Increase the width of your terminal')
sys.exit(1)
def __exit__(self, exc_type, exc_value, traceback):
""" reset terminal settings and de-init curses """
self.stdscr.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
def close(self):
self.text = self.text_orig
curses.endwin()
curses.flushinp()
return False
def finalize(self):
curses.nocbreak()
curses.echo()
curses.endwin()
def cleanup():
curses.nocbreak()
curses.echo()
curses.endwin()
pi.stop()
def __exit__(self):
self.exit = True
curses.curs_set(2)
curses.endwin()
os.system('clear')
def wrapper(func, *args, **kwds):
"""Wrapper function that initializes curses and calls another function,
restoring normal keyboard/screen behavior on error.
The callable object 'func' is then passed the main window 'stdscr'
as its first argument, followed by any other arguments passed to
wrapper().
"""
try:
# Initialize curses
stdscr = curses.initscr()
# Turn off echoing of keys, and enter cbreak mode,
# where no buffering is performed on keyboard input
curses.noecho()
curses.cbreak()
# In keypad mode, escape sequences for special keys
# (like the cursor keys) will be interpreted and
# a special value like curses.KEY_LEFT will be returned
stdscr.keypad(1)
# Start color, too. Harmless if the terminal doesn't have
# color; user can test with has_color() later on. The try/catch
# works around a minor bit of over-conscientiousness in the curses
# module -- the error return from C start_color() is ignorable.
try:
curses.start_color()
except:
pass
return func(stdscr, *args, **kwds)
finally:
# Set everything back to normal
if 'stdscr' in locals():
stdscr.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
def run(self):
"""Continue running the awesome finder until interrupted"""
try:
self.input_stream()
except KeyboardInterrupt:
pass
finally:
curses.endwin()
def _stopWindow(stdscr):
stdscr.erase()
stdscr.refresh()
stdscr.keypad(0)
curses.echo()
curses.curs_set(1)
curses.nocbreak()
curses.endwin()
def _cleanup():
curses.echo()
curses.curs_set(1)
curses.nocbreak()
curses.endwin()
traceback.print_exc()
def teardown(win):
"""
returns console to normal state
:param win: the window
"""
# tear down the console
curses.nocbreak()
if win: win.keypad(0)
curses.echo()
curses.endwin()
def __exit__(self, exc_type, exc_val, exc_tb):
self.window.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
def run_main_loop(self):
self.draw_ui()
self.window.move(1, 1)
while 1:
c = self.window.getch()
if curses.keyname(c) in [b'q', b'Q']:
break
elif c == 27:
break
elif curses.keyname(c) in [b'i', b'I']:
break
self.show_notification_state(uuid_store)
curses.endwin()
def __exit__(self, exc_type, exc_val, exc_tb):
self.window.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
def cleanup(gui, poll, injector, ts, tests, command_line, args):
ts.run = False
if gui:
gui.stop()
if poll:
poll.stop()
if injector:
injector.stop()
'''
# doesn't work
if gui:
for (i, c) in enumerate(gui.orig_colors):
curses.init_color(i, c[0], c[1], c[2])
'''
curses.nocbreak();
curses.echo()
curses.endwin()
dump_artifacts(tests, injector, command_line)
if args.save:
with open(LAST, "w") as f:
f.write(hexlify(cstr2py(tests.r.raw_insn)))
sys.exit(0)
def stop(self):
curses.nocbreak();
curses.echo()
curses.endwin()
def close(self):
curses.endwin()
def matrix(self, args):
try:
core.matrix.main()
except KeyboardInterrupt:
curses.endwin()
curses.curs_set(1)
curses.reset_shell_mode()
curses.echo()