def prompt(self, text, options, default=None):
""" Request input from user """
self.stdscr.addstr(self.row, 0, text)
self.stdscr.addstr(" (" + ",".join(options) + ") ")
if default != None:
self.stdscr.addstr("[" + default + "] ")
self.nextrow()
answer = None
while answer not in options:
curses.echo()
answer = self.stdscr.getstr()
curses.noecho()
if answer == "" and default != None:
answer = default
return answer
python类echo()的实例源码
def prompt_bool(self, text, default):
""" prompt user to enter a boolean """
defaultstr = "y" if default else "n"
self.stdscr.addstr(self.row, 0, text)
self.stdscr.addstr(" [" + defaultstr + "] ")
self.nextrow()
curses.echo()
answer = self.stdscr.getstr()
curses.noecho()
if answer == "":
retval = default
else:
answer = answer.lower()
retval = answer.startswith("y") or answer.startswith("t")
return retval
def prompt_string(self, text, default):
""" prompt user to enter text """
self.stdscr.addstr(self.row, 0, text)
if default != None:
self.stdscr.addstr(" [" + str(default) + "] ")
else:
self.stdscr.addstr(" ")
self.nextrow()
curses.echo()
answer = self.stdscr.getstr()
if answer == "" and default != None:
answer = default
curses.noecho()
return answer
def get_input(self):
self._user_input_label_win.addstr(0, 0, 'input:')
self._user_input_label_win.refresh()
curses.echo()
inputstr = self._user_input_win.getstr(
0,
0,
self.width - self._user_input_win_x).decode(code)
curses.noecho()
if platform.python_version_tuple()[0] == '2':
inputstr = to_unicode(inputstr)
self._user_input_win.clear()
if inputstr == self.panic:
inputstr = ''
self._env._task_time = float('inf')
return inputstr
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 getstr(cls, x=None, y=None, prompt=None):
'''
Get string input from user at position, with optional prompt message.
:param x: optional x value
:param y: optional y value
:param prompt: message to prompt user with, example: "Name: "
:return: the string the user input
'''
x, y = cls._fix_xy(x, y)
if prompt is not None:
cls.WINDOW.addstr(y, x, prompt)
x += len(prompt)
curses.echo()
s = cls.WINDOW.getstr(y, x)
curses.noecho()
return s.decode('utf-8')
def getinstr(self,prompt):
self.scr.nodelay(0)
self.scr.addstr(self.y+2,self.x+1,' '*(self.w-2),curses.color_pair(TOPSTATUS))
self.scr.addstr(self.y+2,self.x+1,prompt,curses.color_pair(TOPSTATUS))
self.scr.refresh()
curses.curs_set(1)
curses.echo()
self.scr.attron(curses.color_pair(TOPSTATUS))
retval = self.scr.getstr(self.y+2,self.x+len(prompt)+1,8)
self.scr.addstr(self.y+2,self.x+len(prompt)+1,str(retval),curses.color_pair(TOPSTATUS))
self.scr.attroff(curses.color_pair(TOPSTATUS))
self.scr.refresh()
curses.noecho()
curses.curs_set(0)
self.scr.nodelay(1)
return retval
def setup(self):
curses.start_color()
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
curses.cbreak()
curses.echo()
lines, cols = self.stdscr.getmaxyx()
self.logwin = self.stdscr.subwin(lines - 2, cols, 0, 0)
self.sepwin = self.stdscr.subwin(1, cols, lines - 2, 0)
self.cmdwin = self.stdscr.subwin(1, cols, lines - 1, 0)
self.logwin.scrollok(True)
self.sepwin.bkgd(curses.color_pair(1))
self.sepwin.refresh()
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 getstr(window, empty_ok=False):
curses.curs_set(1)
curses.echo()
window.clear()
window.move(0, 0)
if empty_ok:
response = window.getstr()
else:
response = b''
while response == b'':
response = window.getstr()
window.clear()
window.refresh()
window.move(0, 0)
curses.curs_set(0)
return response
def curses_input(self, stdscr, row, col, prompt_string, ascii_mode=False):
"""
Get an input string with curses.
Row and col are the start position ot the prompt_string.
"""
curses.echo()
stdscr.addstr(row, col, str(prompt_string), curses.A_REVERSE)
stdscr.addstr(row + 1, col, " " * (curses.COLS - 1))
stdscr.refresh()
input_val = ""
while len(input_val) <= 0:
if ascii_mode:
input_val = chr(stdscr.getch())
break
else:
input_val = stdscr.getstr(row + 1, col, 20)
return input_val
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 __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 show_menu(self, title, items):
""" Show a menu """
done = False
while not done:
self.newpage(title)
self.nextrow()
options = []
for item in items:
self.stdscr.addstr(self.row, 0, " {0}) {1}".format(*item))
options.append(item[0])
self.nextrow()
self.nextrow()
self.stdscr.addstr(self.row, 0, "Select an option (" + ", ".join(options) + "): ")
curses.echo()
answer = self.stdscr.getstr()
curses.noecho()
for item in items:
if answer == item[0]:
if item[2] == None:
done = True
else:
item[2](self)
def finalize(self):
curses.nocbreak()
curses.echo()
curses.endwin()
def cleanup():
curses.nocbreak()
curses.echo()
curses.endwin()
pi.stop()
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 _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 get_string(stdscr, prompt):
'''Requests and string from the user'''
curses.echo()
stdscr.clear()
stdscr.addnstr(0, 0, prompt, -1, curses.color_pair(2))
curses.curs_set(1)
stdscr.refresh()
in_str = stdscr.getstr(1, 0, 20).decode()
curses.noecho()
curses.curs_set(0)
stdscr.clear()
curses.halfdelay(10)
return in_str
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 __exit__(self, exc_type, exc_val, exc_tb):
self.window.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
def disas_ndisasm(b):
b = ''.join('\\x%02x' % ord(c) for c in b)
if arch == "64":
dis, errors = subprocess.Popen("echo -ne '%s' | ndisasm -b64 - | head -2" % b,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()
else:
dis, errors = subprocess.Popen("echo -ne '%s' | ndisasm -b32 - | head -2" % b,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()
dis = dis.split("\n")
extra = dis[1]
dis = dis[0].split(None, 4)
if extra.strip()[0] == '-':
dis[1] = dis[1] + extra.strip()[1:]
address = dis[0]
insn = dis[1]
mnemonic = dis[2]
if len(dis) > 3:
op_str = dis[3]
else:
op_str = ""
if mnemonic == "db":
mnemonic = "(unk)"
insn = ""
op_str = ""
size = len(insn)/2
return (mnemonic, op_str, size)
# objdump disassembler
# (objdump breaks unnecessary prefixes onto its own line, which makes parsing
# the output difficult. really only useful with the -P0 flag to disallow
# prefixes)
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 matrix(self, args):
try:
core.matrix.main()
except KeyboardInterrupt:
curses.endwin()
curses.curs_set(1)
curses.reset_shell_mode()
curses.echo()
def __del__(self):
"""
Reset terminal before quit.
"""
curses.nocbreak()
curses.echo()
curses.endwin()
def run(self):
'''
Runs all the windows added to the application, and returns a `Result`
object.
'''
result = Result()
try:
self.scr = curses.initscr()
self.MAX_HEIGHT, self.MAX_WIDTH = self.scr.getmaxyx()
curses.noecho()
curses.cbreak()
curses.start_color()
curses.use_default_colors()
self.window = self.scr.subwin(0, 0)
self.window.keypad(1)
self.window.nodelay(1)
self._run_windows()
self.threads += [gevent.spawn(self._input_loop)]
gevent.joinall(self.threads)
for thread in self.threads:
if thread.exception:
result._extract_thread_exception(thread)
except KeyboardInterrupt:
result._extract_exception()
except Exception:
result._extract_exception()
finally:
if self.scr is not None:
self.scr.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
return result
def display(self):
curses.setsyx(self._y, self._x)
self._view.scr.clrtoeol()
self._view.string(self._text, 0, 0)
curses.echo()
curses.curs_set(1)
self._view.scr.refresh()
return self