• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python readline.clear_history函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: launch_subshell

    def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context =
            {}):
        """Launch a subshell.

        The doc string of the cmdloop() method explains how shell histories and
        history files are saved and restored.

        The design of the _ShellBase class encourage launching of subshells through
        the subshell() decorator function. Nonetheless, the user has the option
        of directly launching subshells via this method.

        Arguments:
            shell_cls: The _ShellBase class object to instantiate and launch.
            args: Arguments used to launch this subshell.
            prompt: The name of the subshell. The default, None, means
                to use the shell_cls.__name__.
            context: A dictionary to pass to the subshell as its context.

        Returns:
            'root': Inform the parent shell to keep exiting until the root shell
                is reached.
            'all': Exit the the command line.
            False, None, or anything that are evaluated as False: Inform the
                parent shell to stay in that parent shell.
            An integer indicating the depth of shell to exit to. 0 = root shell.
        """
        # Save history of the current shell.
        readline.write_history_file(self.history_fname)

        prompt = prompt if prompt else shell_cls.__name__
        mode = _ShellBase._Mode(
                shell = self,
                cmd = cmd,
                args = args,
                prompt = prompt,
                context = context,
        )
        shell = shell_cls(
                batch_mode = self.batch_mode,
                debug = self.debug,
                mode_stack = self._mode_stack + [ mode ],
                pipe_end = self._pipe_end,
                root_prompt = self.root_prompt,
                stdout = self.stdout,
                stderr = self.stderr,
                temp_dir = self._temp_dir,
        )
        # The subshell creates its own history context.
        self.print_debug("Leave parent shell '{}'".format(self.prompt))
        exit_directive = shell.cmdloop()
        self.print_debug("Enter parent shell '{}': {}".format(self.prompt, exit_directive))

        # Restore history. The subshell could have deleted the history file of
        # this shell via 'history clearall'.
        readline.clear_history()
        if os.path.isfile(self.history_fname):
            readline.read_history_file(self.history_fname)

        if not exit_directive is True:
            return exit_directive
开发者ID:qzmfranklin,项目名称:easyshell,代码行数:60,代码来源:base.py


示例17: clear_history

 def clear_history(self):
     try:
         readline.clear_history()
     except AttributeError:
         len = self.get_max_length()
         readline.set_history_length(0)
         readline.set_history_length(len)
开发者ID:AppScale,项目名称:appscale,代码行数:7,代码来源:history.py


示例18: i

 def i(self):
   """
   Enter in madx command line
   r.i()
   """
   readline.parse_and_bind("tab: complete")
   fn1=home+'/.history_madx'
   fn2=home+'/.ipython/history'
   os.system("touch " + fn1)
   os.system("touch " + fn2)
   print "Type Ctrl-D to enter ipython"
   cmd=''
   readline.clear_history()
   readline.read_history_file(fn1)
   print 'X: ==> '
   try:
     while( 1):
       cmd=cmd+re.sub('\!.*','',raw_input())
       if cmd.endswith(';'):
         self.p(cmd)
         cmd=''
         print 'X: ==> '
   except EOFError:
     pass
   readline.write_history_file(fn1)
   readline.clear_history()
   readline.read_history_file(fn2)
   print "Type madx() to enter MadX"
开发者ID:BenjaminBerhault,项目名称:Python_Classes4MAD,代码行数:28,代码来源:pymad-0.4.py


示例19: get_meta

    def get_meta(prompt, default, default_list):
        default_count = 0
        if default_list:
            if not default:
                count = len(default_list)
                if count == 0:
                    default = ''
                else:
                    if type(default_list[0]) is str:
                        default = default_list[0]
                    else:
                        default = default_list[0][0]
                    default_count = count - 1

            readline.clear_history()
            default_list.reverse()
            for d in default_list:
                if type(d) is str:
                    readline.add_history(d)
                else:
                    readline.add_history(d[0])

        if default_count > 0:
            full_prompt = ('{} [{}](+ {} more): '.
                    format(prompt, default, default_count))
        else:
            full_prompt = ('{} [{}]: '.
                    format(prompt, default))

        result = input(full_prompt)
        if result == '':
            return default
        else:
            return result
开发者ID:bhrebec,项目名称:tennis-datafier,代码行数:34,代码来源:drawsheet.py


示例20: run_tests

def run_tests():
    global CONSUMER_KEY, CONSUMER_SECRET, SERVER_URL
    CONSUMER_KEY = raw_input("consumer key (anyone): ") or "anyone"
    CONSUMER_SECRET = raw_input("consumer secret (anyone): ") or "anyone"
    SERVER_URL = raw_input("server base url (http://www.khanacademy.org): ") \
        or "http://www.khanacademy.org"

    # It's a bit annoying for key/secret to be in readline history
    readline.clear_history()
    print

    get_request_token()
    if not REQUEST_TOKEN:
        print "Did not get request token."
        return

    get_access_token()
    if not ACCESS_TOKEN:
        print "Did not get access token."
        return

    while(True):
        try:
            get_api_resource()
        except EOFError:
            print
            break
        except Exception, e:
            print "Error: %s" % e
开发者ID:MattFaus,项目名称:KhanReporter,代码行数:29,代码来源:test.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python readline.get_begidx函数代码示例发布时间:2022-05-26
下一篇:
Python readline.add_history函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap