Python curses 模块,wrapper() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.wrapper()

项目:HTP    作者:nklose    | 项目源码 | 文件源码
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
项目:unmessage    作者:AnemoneLabs    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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.
项目:ssha    作者:claranet    | 项目源码 | 文件源码
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)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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.
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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.
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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.
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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.
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
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.
项目:ci_edit    作者:google    | 项目源码 | 文件源码
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')
项目:PenguinDome    作者:quantopian    | 项目源码 | 文件源码
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)
项目:notex    作者:adiultra    | 项目源码 | 文件源码
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)
项目:bittyband    作者:yam655    | 项目源码 | 文件源码
def start_jam(self):
        return curses.wrapper(self.switch_jam)
项目:bittyband    作者:yam655    | 项目源码 | 文件源码
def start_list(self):
        return curses.wrapper(self.switch_list)
项目:bittyband    作者:yam655    | 项目源码 | 文件源码
def start_import(self):
        return curses.wrapper(self.switch_import)
项目:bittyband    作者:yam655    | 项目源码 | 文件源码
def start_import_file(self):
        return curses.wrapper(self.switch_import_file)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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()
项目:lgsm-python    作者:jaredballou    | 项目源码 | 文件源码
def __init__(self, type="curses", menudata=None):
        if type == "curses":
            self.menu = curses.wrapper(CursesMenu,menudata=menudata)
项目:cryptop    作者:huwwp    | 项目源码 | 文件源码
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)
项目:reinforcement_learning    作者:andreweskeclarke    | 项目源码 | 文件源码
def play_visually(self):
        curses.wrapper(self.play)
项目:new    作者:atlj    | 项目源码 | 文件源码
def ana():
    curses.wrapper(main)
项目:xcode_archive    作者:zhipengbird    | 项目源码 | 文件源码
def start(self):
        return curses.wrapper (self._start)
项目:ssha    作者:claranet    | 项目源码 | 文件源码
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
项目:isar    作者:ilbers    | 项目源码 | 文件源码
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()
项目:melomaniac    作者:sdispater    | 项目源码 | 文件源码
def launch(self):
        curses.wrapper(self._launch)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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()
项目:aws-ec2rescue-linux    作者:awslabs    | 项目源码 | 文件源码
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)
项目:aws-ec2rescue-linux    作者:awslabs    | 项目源码 | 文件源码
def __call__(self):
        self.row_right = curses.wrapper(self._draw_input, self.header, self.message).strip()
项目:aws-ec2rescue-linux    作者:awslabs    | 项目源码 | 文件源码
def __call__(self):
        while True:
            curses.wrapper(self.setup)
            if self.done:
                return True
项目:aws-ec2rescue-linux    作者:awslabs    | 项目源码 | 文件源码
def show_item_help(self, menu_item):
        return curses.wrapper(self._draw_notification, menu_item.helptext)
项目:nanosat-control    作者:ceyzeriat    | 项目源码 | 文件源码
def start(self):
        curses.wrapper(self.init)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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()
项目:rogueinabox    作者:rogueinabox    | 项目源码 | 文件源码
def start_ui(self):
        curses.wrapper(self._start_ui)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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()
项目:Music-Scraper    作者:srivatsan-ramesh    | 项目源码 | 文件源码
def start_gui(process):
    """
    A function that takes care of starting the GUI and stops the Scrapy crawler process when exited from program.

    :param CrawlerProcess process: The scrapy crawler process that is used to scrape the web. The instance is used for stopping the process.
    """

    def create_ui(screen):
        """
        A function passes to curses wrapper for safe execution of terminal GUI.

        :param screen: The screen parameter to run the GUI. Sent from the curses wrapper.
        """

        GUI.screen = screen  # All the statis variables of the GUI class is initialized
        GUI.strings = []  # the list of songs is empty initially
        GUI.init_display()  # init the variables required for GUI
        GUI.update_on_key()  # Starts a loop that waits for key input and acts accordingly

        curses.nocbreak()
        curses.echo()
        curses.endwin()
        GUI.gui_stopped = True

    curses.wrapper(create_ui)
    process.stop()  # Stopping the scrapy crawler process
项目:Pacbot    作者:HarvardURC    | 项目源码 | 文件源码
def main():
    module = InputModule(ADDRESS, PORT)
    curses.wrapper(lambda scr: module.run())
项目:papis    作者:alejandrogallo    | 项目源码 | 文件源码
def start(self):
        if len(self.options) == 0:
            return ""
        if len(self.options) == 1:
            return self.options[0]
        return curses.wrapper(self._start)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
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()
项目:son-cli    作者:sonata-nfv    | 项目源码 | 文件源码
def start_experiment(self):
        if self.graph_only:
            return

         # start pre-configuration commands
        for vnf_name, cmd_list in self.pre_config_commands.items():
            for cmd in cmd_list:
                self.emu.exec(vnf_name=vnf_name, cmd=cmd)

        # start overload detection
        #if len(self.overload_vnf_list) > 0 :
        self.overload_monitor.start(self.emu)

        # start the profling loop
        self.profiling_thread.start()

        if self.no_display == False:
            # nicely print values
            rows, columns = os.popen('stty size', 'r').read().split()
            # Set the Terminal window size larger than its default
            # to make sure the profiling results are fitting
            if int(rows) < 40 or int(columns) < 130:
                sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=40, cols=130))
            # print something to reset terminal
            print("")
            n = os.system("clear")
            # Add a delay to allow settings to settle...
            time.sleep(1)
            curses.wrapper(self.display_loop)
        else:
            # wait for profiling thread to end
            self.profiling_thread.join()

        # stop overload detection
        self.overload_monitor.stop(self.emu)

        # write results to file
        self.write_results_to_file(self.results_file)

        #finalize the calculation of the performance profile
        self.profile_calc.finalize_graph(show_final=self.no_display)
项目:ipmap-creator    作者:ASP-Labs    | 项目源码 | 文件源码
def __init__(
        self,
        options,
        title='Select',
        arrow="-->",
        footer="Space = toggle, Enter = accept, q = cancel",
        more="...",
        border="||--++++",
        c_selected="[v]",
        c_empty="[ ]"
    ):
        self.title = title
        self.arrow = arrow
        self.footer = footer
        self.more = more
        self.border = border
        self.c_selected = c_selected
        self.c_empty = c_empty
        self.all_options = []

        for option in options:
            self.all_options.append({
                "label": option,
                "selected": False
            })
            self.length = len(self.all_options)

        self.curses_start()
        curses.wrapper(self.curses_loop)
        self.curses_stop()
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def run(args):
    curses.wrapper(main,args)
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def run(args):
    chars = parse_chars(args.chars)
    curses.wrapper(main,args,chars)
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def run(args):
    curses.wrapper(main,args)
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def run(args):
    curses.wrapper(main,args)
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def run(args):
    curses.wrapper(colortest)
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def run(args):
    curses.wrapper(main,args)
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def run(args):
    chars = parse_chars(args.chars)
    curses.wrapper(main,args,chars)
项目:toot    作者:ihabunek    | 项目源码 | 文件源码
def run(self):
        curses.wrapper(self._wrapped_run)
项目:simple-reinforcement-learning    作者:google    | 项目源码 | 文件源码
def start(self):
    '''Initializes the context and starts the run loop.'''
    curses.wrapper(self._capture_window)