当前位置: 首页>>代码示例>>Python>>正文


Python readline.clear_history函数代码示例

本文整理汇总了Python中readline.clear_history函数的典型用法代码示例。如果您正苦于以下问题:Python clear_history函数的具体用法?Python clear_history怎么用?Python clear_history使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了clear_history函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: restore_old_history

 def restore_old_history(self):
     readline.clear_history()
     for line in self._oldHistory:
         if line is None:
             continue
         readline.add_history(line)
     self._oldHistory = []
开发者ID:eucalyptus-qa,项目名称:shared,代码行数:7,代码来源:epdb.py

示例2: run_classic_shell

def run_classic_shell(globals, locals, first_time=[True]):
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
        first_time.pop()
    else:
        banner = ""

    ns = SetPropagatingDict([locals, globals], locals)

    from pudb.settings import get_save_config_path
    from os.path import join
    hist_file = join(
            get_save_config_path(),
            "shell-history")

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        readline.clear_history()
        try:
            readline.read_history_file(hist_file)
        except IOError:
            pass

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)

    cons.interact(banner)

    if HAVE_READLINE:
        readline.write_history_file(hist_file)
开发者ID:asmeurer,项目名称:PuDB,代码行数:32,代码来源:shell.py

示例3: getInput

    def getInput(self):
        out = None
        if self._default == None:
            self._default = datetime.datetime.now(dateutil.tz.tzlocal())
        readline.clear_history()

        # put the default value into history
        readline.add_history(self._formatDate(self._default))

        # try to complete during typing.
        readline.set_completer_delims('\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.comp)

        # get user input until it's acceptable
        while out == None:
            inp = input(self._display + " [{}]: "
                        .format(self._formatDate(self._default)))
            if inp == "?":
                self.printSpec()
            else:
                try:
                    out = self.tryParse(inp.strip(), self._default)
                except Exception as e:
                    # although the value is not acceptable, give user
                    # a chance to modify it.
                    hist = inp.strip()
                    if len(hist) > 0:
                        readline.add_history(inp.strip())
                    self.printSpec()

        readline.clear_history()
        readline.set_completer()
        # print(">> {}: {}".format(self._display, out.strftime("%Y/%m/%d %H:%M")))
        return out
开发者ID:kk1fff,项目名称:caishen,代码行数:35,代码来源:user_input.py

示例4: wrapper

    def wrapper(*args, **kwargs):
        try:
            import readline
            handle_readline = True
        except ImportError:
            handle_readline = False

        if handle_readline:
            # backup & reset readline completer
            old_readline_completer = readline.get_completer()
            readline.set_completer((lambda x: x))
            # backup & reset readline history
            old_readline_history = []
            hist_sz = readline.get_current_history_length()
            for i in range(1, hist_sz + 1):
                line = readline.get_history_item(i)
                old_readline_history.append(line)
            readline.clear_history()

        try:
            retval = function(*args, **kwargs)
        finally:

            if handle_readline:
                # restore old readline completer
                readline.set_completer(old_readline_completer)
                # restore old readline history
                readline.clear_history()
                for line in old_readline_history:
                    readline.add_history(line)

        return retval
开发者ID:nil0x42,项目名称:phpsploit,代码行数:32,代码来源:isolate_readline_context.py

示例5: pudb_shell

def pudb_shell(_globals, _locals):
    """
    This example shell runs a classic Python shell. It is based on
    run_classic_shell in pudb.shell.

    """
    # Many shells only let you pass in a single locals dictionary, rather than
    # separate globals and locals dictionaries. In this case, you can use
    # pudb.shell.SetPropagatingDict to automatically merge the two into a
    # single dictionary. It does this in such a way that assignments propogate
    # to _locals, so that when the debugger is at the module level, variables
    # can be reassigned in the shell.
    from pudb.shell import SetPropagatingDict
    ns = SetPropagatingDict([_locals, _globals], _locals)

    try:
        import readline
        import rlcompleter
        HAVE_READLINE = True
    except ImportError:
        HAVE_READLINE = False

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        readline.clear_history()

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)
    cons.interact("Press Ctrl-D to return to the debugger")
开发者ID:asmeurer,项目名称:PuDB,代码行数:31,代码来源:example-shell.py

示例6: do_history

 def do_history(self, args):
     """
     Prints cloudmonkey history
     """
     if self.pipe_runner("history " + args):
         return
     startIdx = 1
     endIdx = readline.get_current_history_length()
     numLen = len(str(endIdx))
     historyArg = args.split(' ')[0]
     if historyArg.isdigit():
         startIdx = endIdx - long(historyArg)
         if startIdx < 1:
             startIdx = 1
     elif historyArg == "clear" or historyArg == "c":
         readline.clear_history()
         print "CloudMonkey history cleared"
         return
     elif len(historyArg) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit():
         command = readline.get_history_item(long(historyArg[1:]))
         readline.set_startup_hook(lambda: readline.insert_text(command))
         self.hook_count = 1
         return
     for idx in xrange(startIdx, endIdx):
         self.monkeyprint("%s %s" % (str(idx).rjust(numLen),
                                     readline.get_history_item(idx)))
开发者ID:waegemae,项目名称:cloudstack-cloudmonkey,代码行数:26,代码来源:cloudmonkey.py

示例7: get_environment

    def get_environment(self, owner_key):
        environment_list = []
        try:
            if self.cp.supports_resource('environments'):
                environment_list = self.cp.getEnvironmentList(owner_key)
            elif self.options.environment:
                system_exit(os.EX_UNAVAILABLE, _("Environments are not supported by this server."))
        except Exception as e:
            log.exception(e)
            system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e)

        environment = None
        if len(environment_list) > 0:
            if self.options.environment:
                env_input = self.options.environment
            elif len(environment_list) == 1:
                env_input = environment_list[0]['name']
            else:
                env_input = six.moves.input(_("Environment: ")).strip()
                readline.clear_history()

            for env_data in environment_list:
                # See BZ #978001
                if (env_data['name'] == env_input or
                   ('label' in env_data and env_data['label'] == env_input) or
                   ('displayName' in env_data and env_data['displayName'] == env_input)):
                    environment = env_data['name']
                    break
            if not environment:
                system_exit(os.EX_DATAERR, _("Couldn't find environment '%s'.") % env_input)

        return environment
开发者ID:Lorquas,项目名称:subscription-manager,代码行数:32,代码来源:migrate.py

示例8: _save_history

 def _save_history(self, history_file):
     """
     Save the commandline history to the readline history provided
     + Clear the history buffer
     """
     readline.write_history_file(os.path.join(MODULE_LOCATION, history_file))
     readline.clear_history()  
开发者ID:kyrus,项目名称:PyMyo,代码行数:7,代码来源:pyMyoCli.py

示例9: rlinput

def rlinput(prompt, prefill='', oneline=False, ctxkey=''):
    """
    Get user input with readline editing support.
    """

    sentinel = ''
    if prefill is None:
        prefill = ''
    
    def only_once(text):
        """ generator for startup hook """
        readline.insert_text(text)
        yield
        while True:
            yield

    savedhist = NamedTemporaryFile()
    readline.write_history_file(savedhist.name)
    ctxhistname = ".tl" + ctxkey + "history"
    ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname)
    try:
        readline.clear_history()
    except AttributeError:
        print "This readline doesn't support clear_history()"
        raise
    
    savedcompleter = readline.get_completer()
    try:
        ulines = uniqify(ctxhistfile)
        readline.read_history_file(ctxhistfile)
        readline.set_completer(HistoryCompleter(ulines).complete)
    except IOError:
        pass

    readline.parse_and_bind('tab: complete')
    saveddelims = readline.get_completer_delims()
    readline.set_completer_delims('') ## No delims. Complete entire lines.
    readline.set_completion_display_matches_hook(match_display_hook)
    gen = only_once(prefill)
    readline.set_startup_hook(gen.next)
    try:
        if oneline:
            edited = raw_input(prompt)
        else:
            print prompt
            edited = "\n".join(iter(raw_input, sentinel))

        if edited.endswith(r'%%'):
            ## Invoke external editor
            edited = external_edit(edited[0:-2])
        return edited
    finally:
        ## Restore readline state 
        readline.write_history_file(ctxhistfile)
        readline.clear_history()
        readline.read_history_file(savedhist.name)
        savedhist.close()
        readline.set_completer(savedcompleter)
        readline.set_completer_delims(saveddelims)
        readline.set_startup_hook()    
开发者ID:Michael-F-Ellis,项目名称:TransLily,代码行数:60,代码来源:rl_interface.py

示例10: uninit_completer

 def uninit_completer(self):
     try:
         import readline
         readline.set_completer()
         readline.clear_history()
     except:
         pass
开发者ID:kedarmhaswade,项目名称:dx-toolkit,代码行数:7,代码来源:exec_io.py

示例11: run

    def run(self):

        # Preserve existing history
        if self.preserve_history:
            old_history = [readline.get_history_item(index) for index in xrange(readline.get_current_history_length())]
            readline.clear_history()
            map(readline.add_history, self.history)

        readline.set_completer(self.complete)
        readline.parse_and_bind("bind ^I rl_complete")

        while True:
            cmdline = raw_input("%s > " % (self.prefix,))
            self.last_wd_complete = ("", ())
            if not cmdline:
                continue

            # Try to dispatch command
            try:
                self.execute(cmdline)
            except SystemExit, e:
                print "Exiting shell: %s" % (e.code,)
                break
            except UnknownCommand, e:
                print "Command '%s' unknown." % (e,)
开发者ID:muelli,项目名称:CalDAVClientLibrary,代码行数:25,代码来源:baseshell.py

示例12: set_context

    def set_context(self, name):
        """Set the current history context.

        This swaps in a new history context by loading
        the history from the contexts filename.  The
        old context's history is saved first.
        """

        if name not in self.contexts:
            raise ValueError("Invalid history context: %s" % name)

        if self.current:
            if name == self.current.name:
                return
            self.save()

        self.current = self.contexts[name]

        try:
            readline.clear_history()
            if self.current.obj:
                with open(self.current.filename, "r") as f:
                    lines = pickle.load(f)

                for line in lines:
                    readline.add_history(line)

            else:
                readline.read_history_file(self.current.filename)
        except IOError:
            pass
开发者ID:pombredanne,项目名称:steelscript,代码行数:31,代码来源:rest.py

示例13: run

def run(func, *args, **kwargs):
    """pdb hook: invokes pdb on exceptions in python.

    The function func is called, with arguments args and
    kwargs=kwargs.  If this func raises an exception, pdb is invoked
    on that frame.  Upon exit from pdb, return to python normally."""
    # save history
    old_hist = _get_history()
    old_hist_start = readline.get_current_history_length()+1

    try:
        return func(*args, **kwargs)
    except Exception as e:
        _add_history(_run_history)


        t, value, tb = sys.exc_info()
        sys.__excepthook__(t, value, tb)
        frame = sys.exc_info()[2]
        #tb = e.tb_frame
        pdb.post_mortem(tb)
        del frame   # the docs warn to avoid circular references.
        del t, value, tb

        _run_history[:] = _get_history(first=old_hist_start)
    readline.clear_history()
    _restore_history(old_hist)
    print old_hist
开发者ID:CxAalto,项目名称:verkko,代码行数:28,代码来源:pdbtb.py

示例14: handle

    def handle(self, cmd):
        args = cmd.split(' ')
        if args[0] == 'save':
            if len(args) >= 3:
                alias = args[1]
                (host, port) = usc_config.make_addr(args[2:])
                usc_config.save_alias(alias, host, port)
                self.comp.add_to_list("alias", {alias})
        elif args[0] == 'drop':
            if len(args) == 2:
                usc_config.remove_alias(args[1])
        elif args[0] == 'list':
            aliases = usc_config.get_aliases()
            for alias in aliases:
                print(alias + " : " + repr(aliases[alias]))
        elif args[0] == 'connect':
            print("Connecting...")
            c = controller.UscController()
            (host, port) = usc_config.resolve_addr(args[1:])

            readline.write_history_file('.history')
            readline.clear_history()
            # Long call
            c.connect(host, port)
            print("Disconnected.")

            readline.clear_history()
            readline.read_history_file('.history')
            # Done !
            self.refresh()
        elif args[0] == 'quit':
            return True

        return False
开发者ID:gyscos,项目名称:USC,代码行数:34,代码来源:usc_shell.py

示例15: get_org

    def get_org(self, username):
        try:
            owner_list = self.cp.getOwnerList(username)
        except Exception as e:
            log.exception(e)
            system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e)

        if len(owner_list) == 0:
            system_exit(1, _("%s cannot register with any organizations.") % username)
        else:
            if self.options.org:
                org_input = self.options.org
            elif len(owner_list) == 1:
                org_input = owner_list[0]['key']
            else:
                org_input = six.moves.input(_("Org: ")).strip()
                readline.clear_history()

            org = None
            for owner_data in owner_list:
                if owner_data['key'] == org_input or owner_data['displayName'] == org_input:
                    org = owner_data['key']
                    break
            if not org:
                system_exit(os.EX_DATAERR, _("Couldn't find organization '%s'.") % org_input)
        return org
开发者ID:Lorquas,项目名称:subscription-manager,代码行数:26,代码来源:migrate.py


注:本文中的readline.clear_history函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。