def __del__(self):
"""
Reset terminal before quit.
"""
curses.nocbreak()
curses.echo()
curses.endwin()
python类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 cleanup():
"""Cleanup before exiting"""
if not window:
return
w_str = get_window_contents()
curses.curs_set(1)
curses.endwin()
print w_str.rstrip()
print
mixer.quit()
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 __del__(self):
curses.nocbreak()
curses.echo()
curses.endwin()
# print('done')
def close_curses():
mainwindow.keypad(0)
curses.echo()
curses.nocbreak()
curses.curs_set(2)
curses.endwin()
def on_finish(self):
global interpreter
if self.debug and not self.compat_debug:
curses.nocbreak()
self.stdscr.keypad(False)
curses.echo()
curses.endwin()
# sys.exit(0)
def run_stats(url,
stats_update_frequency=3,
endpoint_update_frequency=30,
csv_enable_summary=False,
csv_enable_validator=False
):
try:
# initialize globals when we are read for stats display. This keeps
# curses from messing up the status prints prior to stats start up.
epm = EndpointManager()
sm = StatsManager() # sm assumes epm is created!
# initialize csv stats file generation
print "initializing csv"
sm.csv_init(csv_enable_summary, csv_enable_validator)
# prevent curses import from modifying normal terminal operation
# (suppression of cr-lf) during display of help screen, config settings
if curses_imported:
curses.endwin()
# discover validator endpoints; if successful, continue with startup()
epm.initialize_endpoint_discovery(
url,
startup,
{
'loop_times': {
"stats": stats_update_frequency,
'endpoint': endpoint_update_frequency},
'stats_man': sm,
'ep_man': epm
})
reactor.run()
sm.stats_stop()
except Exception as e:
if curses_imported:
curses.endwin()
sys.stderr.write(e)
raise
def cpstop(self):
if self.use_curses:
curses.nocbreak()
self.scrn.keypad(0)
curses.echo()
curses.endwin()
def send_kill(self, signum, fram):
self.player.stop()
self.cache.quit()
self.storage.save()
curses.endwin()
sys.exit()
def signal_handler(signal, frame):
print 'You pressed Ctrl + C!'
curses.endwin()
sys.exit(0)
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 create_screen(fn):
"""
Initializes curses and passes a Screen to the main loop function `fn`.
Based on curses.wrapper.
"""
try:
# Make escape key more responsive
os.environ['ESCDELAY'] = '25'
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
stdscr.nodelay(1)
curses.curs_set(0)
curses.mousemask(curses.BUTTON1_CLICKED)
if curses.has_colors():
curses.start_color()
curses.use_default_colors()
screen = Screen(stdscr)
fn(screen)
finally:
# Set everything back to normal
if 'stdscr' in locals():
curses.use_default_colors()
curses.curs_set(1)
stdscr.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
def main():
if not sys.argv[1:]:
print __doc__
sys.exit(0)
cmd = " ".join(sys.argv[1:])
p = os.popen(cmd, "r")
text = p.read()
sts = p.close()
if sts:
print >>sys.stderr, "Exit code:", sts
sys.exit(sts)
w = curses.initscr()
try:
while True:
w.erase()
try:
w.addstr(text)
except curses.error:
pass
w.refresh()
time.sleep(1)
p = os.popen(cmd, "r")
text = p.read()
sts = p.close()
if sts:
print >>sys.stderr, "Exit code:", sts
sys.exit(sts)
finally:
curses.endwin()
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 getConsoleWidth(default=80):
"""
Returns console width
"""
width = None
if os.getenv("COLUMNS", "").isdigit():
width = int(os.getenv("COLUMNS"))
else:
try:
try:
FNULL = open(os.devnull, 'w')
except IOError:
FNULL = None
process = subprocess.Popen("stty size", shell=True, stdout=subprocess.PIPE, stderr=FNULL or subprocess.PIPE)
stdout, _ = process.communicate()
items = stdout.split()
if len(items) == 2 and items[1].isdigit():
width = int(items[1])
except (OSError, MemoryError):
pass
if width is None:
try:
import curses
stdscr = curses.initscr()
_, width = stdscr.getmaxyx()
curses.endwin()
except:
pass
return width or default
def __exit__(self, exc_type, exc_val, exc_tb):
# for thread in self.threads:
# thread.join()
curses.noraw()
self.screen.keypad(False)
curses.echo()
curses.endwin()
def main_loop(a_dict, inst_dict, name, version, build_type):
""" This is a simple function with the goal of making scripts that
utilize this interface more clean. It sets all of the vital info,
and runs all of the major loops available in a specific order.
"""
interface = MainInterface(a_dict, inst_dict)
interface.package_name = name
interface.package_version = version
interface.build_type = build_type
interface.init_package_info_entry()
exit_main = False
while not exit_main:
if interface.window == 'build':
exit_main, build_package = interface.run_option_loop()
elif interface.window == 'install':
exit_main, build_package = interface.run_install_loop()
elif interface.window == 'build-help':
exit_main, build_package = interface.run_help_loop('build')
elif interface.window == 'install-help':
exit_main, build_package = interface.run_help_loop('install')
curses.endwin()
if build_package:
return interface.get_return_values()
else:
return False
def close(self):
if not self.enable:
return
curses.nocbreak()
self.stdscr.keypad(0)
curses.echo()
curses.endwin()
def deinit(self):
curses.nocbreak()
self.screen.keypad(False)
curses.echo()
curses.endwin()