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
python类wrapper()的实例源码
def start(self, name,
local_server_ip=None,
local_server_port=None,
launch_tor=True,
tor_socks_port=None,
tor_control_port=None,
remote_mode=False,
local_mode=False):
self.help_info = create_help()
self.remote_mode = remote_mode
if not name:
print 'unMessage could not find a name to use'
print 'Run unMessage with `-name`'
else:
curses.wrapper(self.start_main,
name,
local_server_ip,
local_server_port,
launch_tor,
tor_socks_port,
tor_control_port,
local_mode)
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 choose_instance(instances, search):
labels = [ec2.label(inst) for inst in instances]
columns_width = _find_each_column_width(labels)
items = []
for i, inst in enumerate(instances):
formatted_labels = [label.ljust(columns_width[j]) for j, label in enumerate(labels[i])]
items.append(Item(label=' '.join(formatted_labels), value=inst))
if search:
search = search.lower()
items = [item for item in items if search in item.label.lower()]
if len(items) == 1:
return items[0].value
if not items:
return None
return curses.wrapper(_display, items)
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 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 run_ci():
locale.setlocale(locale.LC_ALL, '')
try:
# Reduce the delay waiting for escape sequences.
os.environ.setdefault('ESCDELAY', '1')
curses.wrapper(wrapped_ci)
finally:
app.log.flush()
app.log.writeToFile('~/.ci_edit/recentLog')
# Disable Bracketed Paste Mode.
sys.stdout.write('\033[?2004l\n')
global userConsoleMessage
if userConsoleMessage:
fullPath = os.path.expanduser(os.path.expandvars(
'~/.ci_edit/userConsoleMessage'))
with io.open(fullPath, 'w+') as f:
f.write(userConsoleMessage)
sys.stdout.write(userConsoleMessage + '\n')
def main():
args = parse_args()
log.info('Requesting remote shell from {}', args.hostname)
with PenguinDomeServerPeer(
'server', local_port=get_setting('local_port'),
logger=log, client_hostname=args.hostname) as remote, \
TerminalPeer() as terminal:
host = args.hostname
script = '#!/bin/bash\npython client/endpoints/shell.py {}\n'.format(
remote.pipe_id)
patch_hosts('client/commands/shell-{}'.format(remote.pipe_id),
patch_content=script.encode('ascii'),
hosts=host)
broker = InteractionBroker(terminal, remote, poll_interval=0.2)
print('Waiting for client to connect (once connected, use "~." to '
'disconnect)...')
remote.poll()
curses.wrapper(interact, broker)
def editor(**kwargs):
os.environ['ESCDELAY'] = '25'
if sys.version_info.major < 3:
lc_all = locale.getlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, '')
else:
lc_all = None
try:
return curses.wrapper(main, **kwargs)
finally:
if lc_all is not None:
locale.setlocale(locale.LC_ALL, lc_all)
def start_jam(self):
return curses.wrapper(self.switch_jam)
def start_list(self):
return curses.wrapper(self.switch_list)
def start_import(self):
return curses.wrapper(self.switch_import)
def start_import_file(self):
return curses.wrapper(self.switch_import_file)
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__(self, type="curses", menudata=None):
if type == "curses":
self.menu = curses.wrapper(CursesMenu,menudata=menudata)
def main():
if os.path.isfile(BASEDIR):
sys.exit('Please remove your old configuration file at {}'.format(BASEDIR))
os.makedirs(BASEDIR, exist_ok=True)
global CONFIG
CONFIG = read_configuration(CONFFILE)
locale.setlocale(locale.LC_MONETARY, CONFIG['locale'].get('monetary', ''))
requests_cache.install_cache(cache_name='api_cache', backend='memory',
expire_after=int(CONFIG['api'].get('cache', 10)))
curses.wrapper(mainc)
def play_visually(self):
curses.wrapper(self.play)
def ana():
curses.wrapper(main)
def start(self):
return curses.wrapper (self._start)
def choose_config(names, search):
if search:
return search
elif len(names) > 1:
items = [Item(label=name, value=name) for name in names]
return curses.wrapper(_display, items)
elif names:
return names[0]
else:
return None
def main(server, eventHandler, params):
if not os.isatty(sys.stdout.fileno()):
print("FATAL: Unable to run 'ncurses' UI without a TTY.")
return
ui = NCursesUI()
try:
curses.wrapper(ui.main, server, eventHandler, params)
except:
import traceback
traceback.print_exc()
def launch(self):
curses.wrapper(self._launch)
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 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 __call__(self):
self.row_right = curses.wrapper(self._draw_input, self.header, self.message).strip()
def __call__(self):
while True:
curses.wrapper(self.setup)
if self.done:
return True
def show_item_help(self, menu_item):
return curses.wrapper(self._draw_notification, menu_item.helptext)