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类noecho()的实例源码
def setup():
"""
sets environment up and creates main window
:returns: the main window object
"""
# setup the console
mmask = curses.ALL_MOUSE_EVENTS # for now accept all mouse events
main = curses.initscr() # get a window object
y,x = main.getmaxyx() # get size
if y < 24 or x < 80: # verify minimum size rqmts
raise RuntimeError("Terminal must be at least 80 x 24")
curses.noecho() # turn off key echoing
curses.cbreak() # turn off key buffering
curses.mousemask(mmask) # accept mouse events
initcolors() # turn on and set color pallet
main.keypad(1) # let curses handle multibyte special keys
main.clear() # erase everything
banner(main) # write the banner
mainmenu(main) # then the min and menu
main.attron(CPS[RED]) # make the border red
main.border(0) # place the border
main.attroff(CPS[RED]) # turn off the red
curses.curs_set(0) # hide the cursor
main.refresh() # and show everything
return main
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
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 initialize(self):
# initialize curses
self._stdscr = curses.initscr()
# TODO generalize this:
begin_x = 0
begin_y = 0
# self._info_win_width = 20
self._info_win_height = 4
self.height, self.width = self._stdscr.getmaxyx()
self._win = self._stdscr.subwin(self.height, self.width, begin_y,
begin_x)
# create info box with reward and time
self._info_win = self._win.subwin(self._info_win_height,
self.width,
0,
0)
curses.noecho()
curses.cbreak()
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 setup(self, stdscr):
self.stdscr = stdscr
# define curses color pairs
set_color_pairs()
# set getch to blocking
self.stdscr.nodelay(0)
# don't echo key strokes on the screen
curses.noecho()
# read keystrokes instantly, without waiting for enter to be pressed
curses.cbreak()
# enable keypad mode
self.stdscr.keypad(1)
# draw the main frame
self.setup_draw()
# find what's the erase character
self.del_char = curses.erasechar()
self.run()
def __init__(self):
self.selected_index_stack = [0]
self.returnString = ""
self.play_in_room = None
self.dir = DirBrowse()
self.selected_index = 0
self.selected_column = 0
self.window = curses.initscr()
curses.start_color()
curses.noecho()
curses.cbreak()
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_RED)
curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLUE)
self.window.keypad(1)
self.draw_ui()
def __init__(self, hosts):
self.stdscr = curses.initscr()
curses.start_color()
self.height, self.width = self.stdscr.getmaxyx()
curses.cbreak()
curses.noecho()
self.stdscr.keypad(1)
self.hosts = hosts
self.format = (
'%(hostname)10.10s '
'%(pid)7.7s '
'%(ppid)7.7s '
'%(pcpu)6.6s '
'%(rss)5.5s '
'%(command)20s'
)
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 __enter__(self):
# Default delay when pressing ESC is too long, at 1000ms
os.environ["ESCDELAY"] = "25"
self.pairs = Pairs()
# Make curses use unicode
locale.setlocale(locale.LC_ALL, "")
self.screen = curses.initscr()
curses.noecho()
# Using raw instead of cbreak() gives us access to CTRL+C and others
curses.raw()
self.screen.keypad(True)
if not self.blocking_events:
self.screen.timeout(33)
curses.start_color()
curses.use_default_colors()
self.hide_cursor()
return self
def __init__(self, enable=True):
self.enable = enable
if not self.enable:
return
self.logger = logging.getLogger('trader-logger')
self.stdscr = curses.initscr()
self.pad = curses.newpad(23, 120)
self.order_pad = curses.newpad(10, 120)
self.timestamp = ""
self.last_order_update = 0
curses.start_color()
curses.noecho()
curses.cbreak()
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED)
self.stdscr.keypad(1)
self.pad.addstr(1, 0, "Waiting for a trade...")
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 __init__(self):
self.stdscr = curses.initscr()
# don't display keys
curses.noecho()
# don't need key + enter
curses.cbreak()
# remove cursor
curses.curs_set(0)
self.stdscr.keypad(1)
#stdscr.border(0)
self.height, self.width = self.stdscr.getmaxyx()
self.header = self.stdscr.subwin(3, self.width, 0, 0)
self.header.box()
self.main_win = self.stdscr.subwin(20, self.width-2, 3, 1)
self.main_win.scrollok(True)
self.setup_colours()
# self.main()
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 initialize(self):
# initialize curses
self._stdscr = curses.initscr()
# TODO generalize this:
begin_x = 0
begin_y = 0
# self._info_win_width = 20
self._info_win_height = 4
self.height, self.width = self._stdscr.getmaxyx()
self._win = self._stdscr.subwin(self.height, self.width, begin_y,
begin_x)
# create info box with reward and time
self._info_win = self._win.subwin(self._info_win_height,
self.width,
0,
0)
curses.noecho()
curses.cbreak()
def _create_desktop(self):
global _s_screen
_s_screen = curses.initscr()
curses.noecho()
curses.curs_set(0)
curses.start_color()
self._desktop = Form(None, 0, 0)
self._stats = Form(self._desktop, 0, 0, 70, 20)
self._stats.set_centering(True, True)
self._title = Label(self._stats, 0, 0, 'S2E')
self._title.set_centering(True, False)
self._exitmsg = Label(self._stats, 0, 17, 'Press q to exit')
self._exitmsg.set_centering(True, False)
self._table = Table(self._stats, 2, 2, self._data, self._legend,
self._layout)
self._table.set_centering(True, True)
def initialize(self):
# initialize curses
self._stdscr = curses.initscr()
# TODO generalize this:
begin_x = 0
begin_y = 0
# self._info_win_width = 20
self._info_win_height = 4
self.height, self.width = self._stdscr.getmaxyx()
self._win = self._stdscr.subwin(self.height, self.width, begin_y,
begin_x)
# create info box with reward and time
self._info_win = self._win.subwin(self._info_win_height,
self.width,
0,
0)
curses.noecho()
curses.cbreak()
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 __enter__(self):
""" init curses library """
self.stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
self.stdscr.keypad(1)
return self
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 initialize(self):
# initialize curses
self._stdscr = curses.initscr()
begin_x = 0
begin_y = 0
self._teacher_seq_y = 0
self._learner_seq_y = 1
self._reward_seq_y = 2
self._world_win_y = 4
self._world_win_x = 0
self._info_win_width = 20
self._info_win_height = 4
self._user_input_win_y = 4
self._user_input_win_x = 10
self.height, self.width = self._stdscr.getmaxyx()
self._scroll_msg_length = self.width - self._info_win_width - 1
self._win = self._stdscr.subwin(self.height, self.width, begin_y,
begin_x)
self._worldwin = self._win.subwin(self.height - self._world_win_y,
self.width - self._world_win_x,
self._world_win_y,
self._world_win_x)
# create info box with reward and time
self._info_win = self._win.subwin(self._info_win_height,
self._info_win_width,
0,
self.width - self._info_win_width)
self._user_input_win = \
self._win.subwin(1,
self.width - self._user_input_win_x,
self._user_input_win_y,
self._user_input_win_x)
self._user_input_label_win = \
self._win.subwin(1,
self._user_input_win_x - 1,
self._user_input_win_y,
0)
curses.noecho()
curses.cbreak()
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 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 init_curses(self):
"""Setup the curses"""
self.window = curses.initscr()
self.window.keypad(True)
curses.noecho()
curses.cbreak()
curses.start_color()
curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)
self.current = curses.color_pair(2)
def _startWindow():
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
curses.curs_set(0)
return stdscr
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 tetris_print(array, reward, screen):
curses.noecho()
curses.curs_set(0)
screen.erase()
for y, row in reversed(list(enumerate(array[0]))):
for x, value in enumerate(row):
character = "\u2588" if value else "."
color = curses.color_pair(value)
screen.addch(len(array[0]) - y, 3*x, character, color)
screen.addch(len(array[0]) - y, 3*x + 1, character, color)
screen.addstr(len(array[0]) + 5, 0, 'Reward: {}'.format(reward))
screen.refresh()