當前位置: 首頁>>代碼示例>>Python>>正文


Python readline.add_history方法代碼示例

本文整理匯總了Python中readline.add_history方法的典型用法代碼示例。如果您正苦於以下問題:Python readline.add_history方法的具體用法?Python readline.add_history怎麽用?Python readline.add_history使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在readline的用法示例。


在下文中一共展示了readline.add_history方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _history_update

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def _history_update(self, array=None):
        if array is None:
            array = []
        try:
            import readline
            # add array elements to readline history
            for command in array:
                readline.add_history(command)
            # recreate Hist from readline history (UGLY)
            self.Hist.clear()
            history_len = readline.get_current_history_length()
            for i in range(1, history_len + 1):
                line = readline.get_history_item(i)
                self.Hist.append(line)
        except ImportError:
            pass
        # By default, hist max size is 20% of CACHE_SIZE
        max_size = int(self.Conf["CACHE_SIZE"]() * 0.2)
        # Settle Hist object to its max size
        while self.Hist.size > max_size:
            self.Hist.pop(0) 
開發者ID:nil0x42,項目名稱:phpsploit,代碼行數:23,代碼來源:__init__.py

示例2: testHistoryUpdates

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def testHistoryUpdates(self):
        readline.clear_history()

        readline.add_history("first line")
        readline.add_history("second line")

        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "first line")
        self.assertEqual(readline.get_history_item(2), "second line")

        readline.replace_history_item(0, "replaced line")
        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "replaced line")
        self.assertEqual(readline.get_history_item(2), "second line")

        self.assertEqual(readline.get_current_history_length(), 2)

        readline.remove_history_item(0)
        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "second line")

        self.assertEqual(readline.get_current_history_length(), 1) 
開發者ID:ShikyoKira,項目名稱:Project-New-Reign---Nemesis-Main,代碼行數:24,代碼來源:test_readline.py

示例3: test_nonascii_history

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def test_nonascii_history(self):
        readline.clear_history()
        try:
            readline.add_history("entrée 1")
        except UnicodeEncodeError as err:
            self.skipTest("Locale cannot encode test data: " + format(err))
        readline.add_history("entrée 2")
        readline.replace_history_item(1, "entrée 22")
        readline.write_history_file(TESTFN)
        self.addCleanup(os.remove, TESTFN)
        readline.clear_history()
        readline.read_history_file(TESTFN)
        if is_editline:
            # An add_history() call seems to be required for get_history_
            # item() to register items from the file
            readline.add_history("dummy")
        self.assertEqual(readline.get_history_item(1), "entrée 1")
        self.assertEqual(readline.get_history_item(2), "entrée 22") 
開發者ID:ShikyoKira,項目名稱:Project-New-Reign---Nemesis-Main,代碼行數:20,代碼來源:test_readline.py

示例4: set_history

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def set_history(self, hist):
        for h in hist:
            readline.add_history(h) 
開發者ID:plasma-disassembler,項目名稱:plasma,代碼行數:5,代碼來源:console.py

示例5: _exec_from_file

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def _exec_from_file(self, filename, quiet=False, skip_history=False,
                        print_comments=config['POST_EDIT_PRINT_COMMENTS']):
        self._skip_subsequent = False
        previous = ''
        for stmt in open(filename):
            # - skip over multiple empty lines
            stripped = stmt.strip()
            if stripped == previous == '':
                continue

            # - if line is a comment, print (if required) and move to
            # next line
            if stripped.startswith('#'):
                if print_comments and not quiet:
                    self.write(grey("... {}".format(stmt), bold=False))
                continue

            # - process line only if we haven't encountered an error yet
            if not self._skip_subsequent:
                line = stmt.strip('\n')
                if line and not line[0].isspace():
                    # - end of previous statement, submit buffer for
                    # execution
                    source = "\n".join(self.buffer)
                    more = self.runsource(source, self.filename)
                    if not more:
                        self.resetbuffer()

            if not quiet:
                self.write(cyan("... {}".format(stmt), bold=(not self._skip_subsequent)))

            if self._skip_subsequent:
                self.session_history.append(stmt)
            else:
                self.buffer.append(line)
                if not skip_history:
                    readline.add_history(line)
            previous = stripped
        self.push('') 
開發者ID:lonetwin,項目名稱:pythonrc,代碼行數:41,代碼來源:pythonrc.py

示例6: test_write_read_append

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def test_write_read_append(self):
        hfile = tempfile.NamedTemporaryFile(delete=False)
        hfile.close()
        hfilename = hfile.name
        self.addCleanup(unlink, hfilename)

        # test write-clear-read == nop
        readline.clear_history()
        readline.add_history("first line")
        readline.add_history("second line")
        readline.write_history_file(hfilename)

        readline.clear_history()
        self.assertEqual(readline.get_current_history_length(), 0)

        readline.read_history_file(hfilename)
        self.assertEqual(readline.get_current_history_length(), 2)
        self.assertEqual(readline.get_history_item(1), "first line")
        self.assertEqual(readline.get_history_item(2), "second line")

        # test append
        readline.append_history_file(1, hfilename)
        readline.clear_history()
        readline.read_history_file(hfilename)
        self.assertEqual(readline.get_current_history_length(), 3)
        self.assertEqual(readline.get_history_item(1), "first line")
        self.assertEqual(readline.get_history_item(2), "second line")
        self.assertEqual(readline.get_history_item(3), "second line")

        # test 'no such file' behaviour
        os.unlink(hfilename)
        with self.assertRaises(FileNotFoundError):
            readline.append_history_file(1, hfilename)

        # write_history_file can create the target
        readline.write_history_file(hfilename) 
開發者ID:ShikyoKira,項目名稱:Project-New-Reign---Nemesis-Main,代碼行數:38,代碼來源:test_readline.py

示例7: _add_history

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def _add_history(self, line):
        """Adds the given line to readline history, only if the line
        is non-empty.
        """
        if line and HAS_READLINE:
            readline.add_history(line) 
開發者ID:okpy,項目名稱:ok-client,代碼行數:8,代碼來源:unlock.py

示例8: load_history

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def load_history(self):
        """Load saved command history from local history file"""
        try:
            with file(self.history_file_name, 'r') as f:
                for line in f.readlines():
                    stripped_line = line.strip()
                    self.history.append(stripped_line)
                    readline.add_history(stripped_line)
        except IOError:
            pass  # ignore if file cannot be read 
開發者ID:opencord,項目名稱:voltha,代碼行數:12,代碼來源:main.py

示例9: isolate_io_context

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def isolate_io_context(function):
    """A decorator for separating I/O context.

    This decorator isolates I/O context of target
    function or method.

    I/O Context is a mix of terminal related elements,
    such as current stdout and readline completer
    attributes.

    This decorator is useful if you run something
    that reconfigures the readline completer, or
    needs to use the default stdout file descriptor
    instead of the phpsploit's stdout 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()
        # backup & reset stdout
        old_stdout = sys.stdout
        sys.stdout = sys.__stdout__

        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)
            # restore old stdout
            sys.stdout = old_stdout

        return retval
    return wrapper 
開發者ID:nil0x42,項目名稱:phpsploit,代碼行數:55,代碼來源:isolate_io_context.py

示例10: isolate_readline_context

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def isolate_readline_context(function):
    """A decorator for separating readline context.

    This decorator isolates readline context of target
    function or method.

    Use when phpsploit's readline context should be
    reset temporarly is the context of triggering
    function or method.

    Unlike `isolate_io_context`, this decorator keeps
    original stdout 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
    return wrapper 
開發者ID:nil0x42,項目名稱:phpsploit,代碼行數:48,代碼來源:isolate_readline_context.py

示例11: init

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def init():
    stdout.write("\033[95m----------------------------------------------------------------\n")
    if os.getenv('PYSESSION_SAVE_OFF'):
        PySession.off()
        stdout.write(BANNER_OFF)
    elif os.getenv('PYSESSION_SAVE_LOCALLY'):
        PySession.local()
        stdout.write(BANNER_LOCAL)
    else:
        stdout.write(BANNER_GIST)

    if os.getenv('PYSESSION_SAVE_OFF'):
        stdout.write(BANNER_ENABLE)
    else:
        stdout.write(BANNER_DISABLE)

    stdout.write(BANNER_SWITCH)
    stdout.write("----------------------------------------------------------------\033[0m\n")


    PySession.load_history_urls()
    try:
        from IPython import get_ipython
        PySession.ipython_history = get_ipython().pt_cli.application.buffer.history
        PySession.is_ipython = True
    except (ImportError, AttributeError):
        pass

    if PySession.is_ipython:
        PySession.start_index = len(PySession.ipython_history)

        def custom_hook(shell, etype, evalue, traceback, tb_offset=None):
            PySession.wrong_code_lines.append(
                len(PySession.ipython_history) - 1)
            shell.showtraceback((etype, evalue, traceback),
                                tb_offset=tb_offset)

        get_ipython().set_custom_exc((Exception,), custom_hook)
    else:
        readline.add_history('')  # A hack for a strange bug in 3 < Py <3.5.2
        PySession.start_index = readline.get_current_history_length() + 1

        default_hook = sys.excepthook

        def custom_hook(etype, evalue, traceback):
            PySession.wrong_code_lines.append(
                readline.get_current_history_length())
            default_hook(etype, evalue, traceback)

        sys.excepthook = custom_hook 
開發者ID:FallibleInc,項目名稱:pysession,代碼行數:52,代碼來源:pysession.py

示例12: multiline

# 需要導入模塊: import readline [as 別名]
# 或者: from readline import add_history [as 別名]
def multiline(self, firstline=''):
        full_input = []
        # keep a list of the entries that we've made in history
        old_hist = []
        if firstline:
            full_input.append(firstline)
        while True:
            if hasReadline:
                # add the current readline position
                old_hist.append(readline.get_current_history_length())
            if self.use_rawinput:
                try:
                    line = raw_input(self.multiline_prompt)
                except EOFError:
                    line = 'EOF'
            else:
                self.stdout.write(self.multiline_prompt)
                self.stdout.flush()
                line = self.stdin.readline()
                if not len(line):
                    line = 'EOF'
                else:
                    line = line[:-1] # chop \n
            if line == 'EOF':
                print
                break
            full_input.append(line)
            if ';' in line:
                break

        # add the final readline history position
        if hasReadline:
            old_hist.append(readline.get_current_history_length())

        cmd = ' '.join(full_input)
        if hasReadline:
            # remove the old, individual readline history entries.

            # first remove any duplicate entries
            old_hist = sorted(set(old_hist))

            # Make sure you do this in reversed order so you move from
            # the end of the history up.
            for pos in reversed(old_hist):
                # get_current_history_length returns pos + 1
                readline.remove_history_item(pos - 1)
            # now add the full line
            readline.add_history(cmd)

        return cmd 
開發者ID:sassoftware,項目名稱:conary,代碼行數:52,代碼來源:shell.py


注:本文中的readline.add_history方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。