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类initscr()的实例源码
def __init__(self, username):
os.environ.setdefault('ESCDELAY', '25') # shorten esc delay
self.username = username
# set up IRC
self.channel = "##HTP"
# set up curses
self.scr = curses.initscr()
self.disconnect = False
curses.start_color()
self.scr_height, self.scr_width = self.scr.getmaxyx()
self.chatbar = curses.newwin(5, self.scr_height - 1, 5, 10)
self.msg_text = ''
self.logfile = '../data/irc.txt'
self.log_text = []
# curses color config
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
# start the client
try:
curses.wrapper(self.start_loop())
except Exception as e:
self.scr.addstr(2, 0, str(e), curses.A_REVERSE)
# client game loop
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 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 initscr():
import _curses, curses
# we call setupterm() here because it raises an error
# instead of calling exit() in error cases.
setupterm(term=_os.environ.get("TERM", "unknown"),
fd=_sys.__stdout__.fileno())
stdscr = _curses.initscr()
for key, value in _curses.__dict__.items():
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
setattr(curses, key, value)
return stdscr
# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
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 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 test_main_menu_config_global_module_removal(self, write_config_mock):
"""Test removal of a module named Global."""
original_length = len(self.ec2rl._modules)
global_mod = ec2rlcore.module.get_module("test/modules/bad_mod.d/global.yaml")
self.ec2rl._modules.append(global_mod)
self.assertNotEqual(len(self.ec2rl._modules), original_length)
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
with contextlib.redirect_stdout(self.output):
self.assertTrue(self.ec2rl.menu_config())
self.assertEqual(len(self.output.getvalue()), 129)
self.assertTrue(re.match(r"^\n----------\[Configuration File\]----------\n\nConfiguration file saved:\n"
r"/var/tmp/ec2rl/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}_[0-9]{2}_[0-9]{2}.[0-9]{6}"
r"/configuration.cfg\n$",
self.output.getvalue()))
self.assertEqual(len(self.ec2rl._modules), original_length)
self.assertTrue("Global" not in self.ec2rl._modules)
self.assertTrue(write_config_mock.called)
def test_menu_config_global_arg_selection(self):
"""Test setting the Global arg 'only-domains' to 'performance'"""
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(" ")
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(" ")
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(" ")
# This key sequence may need to change if the Global args in the menu are modified.
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
curses.ungetch("\n")
self.menu()
self.assertFalse(self.menu["Configure global module arguments"]["only-domains"]["application"].toggled)
self.assertFalse(self.menu["Configure global module arguments"]["only-domains"]["net"].toggled)
self.assertFalse(self.menu["Configure global module arguments"]["only-domains"]["os"].toggled)
self.assertTrue(self.menu["Configure global module arguments"]["only-domains"]["performance"].toggled)
def test_menu_config_global_arg_clear_int_index(self):
"""
Test setting that the "Clear" footer option sets the Concurrency value to an empty string.
Verify using an integer index (e.g. list access).
"""
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_LEFT)
curses.ungetch(curses.KEY_LEFT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch(curses.KEY_RIGHT)
# This key sequence may need to change if the Global args in the menu are modified.
curses.ungetch("\n")
curses.ungetch("1")
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch("\n")
self.menu()
self.assertEqual(self.menu["Configure global module arguments"][3].get_value(), "")
def test_menu_config_menu_scrolling_up(self):
"""Test paging down to the bottom of the Modules sub-menu thens scrolling up to the top."""
curses.initscr()
# Exit the menu
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
# Test scrolling up to the top
for i in range(len(self.modules)):
curses.ungetch(curses.KEY_UP)
# Go to the bottom of the Modules sub-menu
for iteration in range(15):
curses.ungetch(curses.KEY_NPAGE)
# Get into the Modules submenu
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
self.assertTrue(self.menu())
def test_menu_config_menu_scrolling_down(self):
"""Test scrolling down through the Modules sub-menu."""
curses.initscr()
# Exit the menu
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
# Test scrolling down, line by line
for i in range(len(self.modules)):
curses.ungetch(curses.KEY_DOWN)
# Get into the Modules submenu
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
self.assertTrue(self.menu())
def test_menu_config_menu_scrolling_down_single_page(self):
"""Test scrolling down through the Global sub-menu."""
curses.initscr()
# Exit the menu
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
# Test scrolling down, line by line, and one past the bottom
for i in range(len(self.menu["Configure global module arguments"])):
curses.ungetch(curses.KEY_DOWN)
# Get into the Global submenu
curses.ungetch("\n")
self.assertTrue(self.menu())
def test_menu_config_toggle_all_off(self):
"""Test that "N" deselects all items in the only-classes menu."""
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
# Deselect all items
curses.ungetch("N")
curses.ungetch("\n")
curses.ungetch("\n")
self.assertTrue(self.menu())
for item in self.menu["Configure global module arguments"]["only-classes"]:
self.assertFalse(item.toggled)
def test_menu_config_toggle_all_on_mixed_items(self):
"""Test that "N" deselects then selects "perfimpact" in the Global args menu."""
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
# Select all items (turns perfimpact on)
curses.ungetch("N")
# Deselect all items (perfimpact is already off)
curses.ungetch("N")
# Toggle perfimpact off
curses.ungetch(" ")
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch("\n")
self.assertTrue(self.menu())
self.assertTrue(self.menu["Configure global module arguments"]["perfimpact"].toggled)
def test_menu_config_view_module_help(self):
"""
Test drawing the menu, selecting the modules menu, a module, and the module help, and then exiting the menu.
"""
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
# _draw_notifications only reacts to ord("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
self.assertTrue(self.menu())
def test_menu_config_view_long_module_help(self):
"""
Test drawing the menu, selecting the modules menu, a module, and the module help, and then exiting the menu.
In this test the help string is more (separated) lines than the window and should be truncated by the
_draw_notification method.
"""
# TODO working here
num_messages = 0
while num_messages < 100:
self.menu["View all modules"]["aptlog"].helptext += "a\n"
num_messages += 1
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
self.assertTrue(self.menu())
def test_menu_config_set_module_value(self):
"""Test drawing module option menu, configuring the period module option, and then exiting the menu."""
curses.initscr()
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch(curses.KEY_RIGHT)
curses.ungetch("\n")
curses.ungetch("1")
curses.ungetch("\n")
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch(curses.KEY_DOWN)
curses.ungetch("\n")
curses.ungetch(curses.KEY_DOWN)
self.assertTrue(self.menu())
self.assertEqual(self.menu["View all modules"]["atop"]["period"].get_value(),
"1")
def initscr():
import _curses, curses
# we call setupterm() here because it raises an error
# instead of calling exit() in error cases.
setupterm(term=_os.environ.get("TERM", "unknown"),
fd=_sys.__stdout__.fileno())
stdscr = _curses.initscr()
for key, value in _curses.__dict__.items():
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
setattr(curses, key, value)
return stdscr
# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
def initscr():
import _curses, curses
# we call setupterm() here because it raises an error
# instead of calling exit() in error cases.
setupterm(term=_os.environ.get("TERM", "unknown"),
fd=_sys.__stdout__.fileno())
stdscr = _curses.initscr()
for key, value in _curses.__dict__.items():
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
setattr(curses, key, value)
return stdscr
# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
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 initscr():
import _curses, curses
# we call setupterm() here because it raises an error
# instead of calling exit() in error cases.
setupterm(term=_os.environ.get("TERM", "unknown"),
fd=_sys.__stdout__.fileno())
stdscr = _curses.initscr()
for key, value in _curses.__dict__.items():
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
setattr(curses, key, value)
return stdscr
# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
def initscr():
import _curses, curses
# we call setupterm() here because it raises an error
# instead of calling exit() in error cases.
setupterm(term=_os.environ.get("TERM", "unknown"),
fd=_sys.__stdout__.fileno())
stdscr = _curses.initscr()
for key, value in _curses.__dict__.items():
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
setattr(curses, key, value)
return stdscr
# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
def initscr():
import _curses, curses
# we call setupterm() here because it raises an error
# instead of calling exit() in error cases.
setupterm(term=_os.environ.get("TERM", "unknown"),
fd=_sys.__stdout__.fileno())
stdscr = _curses.initscr()
for key, value in _curses.__dict__.items():
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
setattr(curses, key, value)
return stdscr
# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
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 get_screen(self):
self.screen = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
if self.x == 0:
starty, startx = self.screen.getmaxyx()
self.x = startx
self.y = starty
resize = curses.is_term_resized(self.y, self.x)
# Action in loop if resize is True:
if resize is True:
y, x = self.screen.getmaxyx()
self.screen.clear()
curses.resizeterm(self.y, self.x)
self.screen.refresh()
self.show_header()
return self.screen
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()