Python readline.get_current_history_length() Examples

The following are 27 code examples of readline.get_current_history_length(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module readline , or try the search function .
Example #1
Source File: test_readline.py    From android_universal with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: __init__.py    From phpsploit with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: test_readline.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: StdinCache.py    From ufora with Apache License 2.0 6 votes vote down vote up
def refreshFromReadline(self):
        """Consume as much content as possible from the line buffer.

        Returns self, so that we can chain calls to this function and 'getlines'.
        """
        newLines = []

        #for some reason, this import segfaults if we do it as part of our routine
        #setup in the test harness. Putting the import here ensures we only
        #import it when we are actively using it (e.g. there is a terminal connected
        #to stdin)
        import readline

        while len(self.lines) + len(newLines) < readline.get_current_history_length():
            newLines.append(readline.get_history_item(len(self.lines) + len(newLines) + 1) + "\n")

        self.lines += newLines
        for block in self.divideIntoBlocks(newLines):
            self.addBlock(block)

        return self 
Example #5
Source File: asadm.py    From aerospike-admin with Apache License 2.0 5 votes vote down vote up
def do_exit(self, line):
        self.close()
        if not self.execute_only_mode and readline.get_current_history_length() > 0:
            readline.write_history_file(self.admin_history)

        return True 
Example #6
Source File: test_readline.py    From android_universal with MIT License 5 votes vote down vote up
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) 
Example #7
Source File: completion.py    From polysh with GNU General Public License v2.0 5 votes vote down vote up
def remove_last_history_item() -> None:
    """The user just typed a password..."""
    last = readline.get_current_history_length() - 1
    readline.remove_history_item(last) 
Example #8
Source File: interactive.py    From rainbowstream with MIT License 5 votes vote down vote up
def get_history_items():
    """
    Get all history item
    """
    return [
        readline.get_history_item(i)
        for i in xrange(1, readline.get_current_history_length() + 1)
    ] 
Example #9
Source File: test_readline.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #10
Source File: pysession.py    From pysession with MIT License 5 votes vote down vote up
def process_history():
    """Processes python shell history to an array of code lines"""
    end_index = len(PySession.ipython_history) - 1 if PySession.is_ipython \
        else readline.get_current_history_length()

    lines_of_code = []
    for i in range(PySession.start_index, end_index):
        if i in PySession.wrong_code_lines:
            continue
        if PySession.is_ipython:
            line = PySession.ipython_history[i]
        else:
            line = readline.get_history_item(i)

        # remove 'exit' and PySession keywords from code
        if line.strip() in ['PySession.local()',
                            'PySession.gist()',
                            'PySession.off()',
                            'exit',
                            'exit()']:
            continue
        lines_of_code.append(line)

    if len(
            lines_of_code) > 0 and lines_of_code[-1] != '\n':  # adding extra last newline
        lines_of_code.append('\n')

    return lines_of_code 
Example #11
Source File: spinel-cli.py    From pyspinel with Apache License 2.0 5 votes vote down vote up
def do_history(self, _line):
        """
        history

          Show previously executed commands.
        """

        try:
            import readline
            hist = readline.get_current_history_length()
            for idx in range(1, hist + 1):
                self.log(readline.get_history_item(idx))
        except ImportError:
            pass 
Example #12
Source File: main.py    From kitty with GNU General Public License v3.0 5 votes vote down vote up
def get_history_items() -> List[str]:
    return list(map(readline.get_history_item, range(1, readline.get_current_history_length() + 1))) 
Example #13
Source File: history.py    From sdb with Apache License 2.0 5 votes vote down vote up
def _call(self, objs: Iterable[drgn.Object]) -> None:
        stop = readline.get_current_history_length() + 1
        if self.args.count is not None:
            start = stop - self.args.count
        else:
            start = 1
        for i in range(start, stop):
            print(f"{i:5}  {readline.get_history_item(i)}") 
Example #14
Source File: interface.py    From phpsploit with GNU General Public License v3.0 5 votes vote down vote up
def do_history(self, argv):
        """Command line history

        SYNOPSIS:
            history [<COUNT>]

        DESCRIPTION:
            Returns a formatted string giving the event number and
            contents for each of the events in the history list
            except for current event.

            If [COUNT] is specified, only the [COUNT] most recent
            events are displayed.

            > history
              - Display the full history of events.
            > history 10
              - Display last 10 commands of the history.
        """
        import readline

        argv.append('9999999999')

        try:
            count = int(argv[1])
        except ValueError:
            return self.interpret("help history")

        last = readline.get_current_history_length()
        while last > session.Hist.MAX_SIZE:
            readline.remove_history_item(0)
            last -= 1
        first = last - count
        if first < 1:
            first = 1
        for i in range(first, last):
            cmd = readline.get_history_item(i)
            print("{:4d}  {:s}".format(i, cmd))

    ####################
    # COMMAND: exploit # 
Example #15
Source File: console.py    From plasma with GNU General Public License v3.0 5 votes vote down vote up
def get_history(self):
        hist = []
        for i in range(readline.get_current_history_length()):
             hist.append(readline.get_history_item(i + 1))
        return hist 
Example #16
Source File: readline.py    From daudin with MIT License 5 votes vote down vote up
def setupReadline(local):
    """Initialize the readline library and command history.

    @return: A C{bool} to indicate whether standard input is a terminal
        (and therefore interactive).
    """
    readline.parse_and_bind('tab: complete')
    readline.set_completer_delims(' \t\n')
    readline.set_completer(Completer(local).complete)

    # Readline code from https://docs.python.org/3.7/library/readline.html
    histfile = os.path.join(os.path.expanduser('~'), '.daudin_history')

    try:
        readline.read_history_file(histfile)
        historyLen = readline.get_current_history_length()
    except FileNotFoundError:
        open(histfile, 'wb').close()
        historyLen = 0

    try:
        readline.append_history_file
    except AttributeError:
        # We won't be able to save readline history. This can happen on
        # Python 3.5 at least - not sure why.
        pass
    else:
        import atexit

        def saveHistory(prevHistoryLen, histfile):
            newHistoryLen = readline.get_current_history_length()
            readline.set_history_length(1000)
            readline.append_history_file(newHistoryLen - prevHistoryLen,
                                         histfile)

        atexit.register(saveHistory, historyLen, histfile)

    return True 
Example #17
Source File: site.py    From Imogen with MIT License 4 votes vote down vote up
def enablerlcompleter():
    """Enable default readline configuration on interactive prompts, by
    registering a sys.__interactivehook__.

    If the readline module can be imported, the hook will set the Tab key
    as completion key and register ~/.python_history as history file.
    This can be overridden in the sitecustomize or usercustomize module,
    or in a PYTHONSTARTUP file.
    """
    def register_readline():
        import atexit
        try:
            import readline
            import rlcompleter
        except ImportError:
            return

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file.
        readline_doc = getattr(readline, '__doc__', '')
        if readline_doc is not None and 'libedit' in readline_doc:
            readline.parse_and_bind('bind ^I rl_complete')
        else:
            readline.parse_and_bind('tab: complete')

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        if readline.get_current_history_length() == 0:
            # If no history was loaded, default to .python_history.
            # The guard is necessary to avoid doubling history size at
            # each interpreter exit when readline was already configured
            # through a PYTHONSTARTUP hook, see:
            # http://bugs.python.org/issue5845#msg198636
            history = os.path.join(os.path.expanduser('~'),
                                   '.python_history')
            try:
                readline.read_history_file(history)
            except OSError:
                pass

            def write_history():
                try:
                    readline.write_history_file(history)
                except (FileNotFoundError, PermissionError):
                    # home directory does not exist or is not writable
                    # https://bugs.python.org/issue19891
                    pass

            atexit.register(write_history)

    sys.__interactivehook__ = register_readline 
Example #18
Source File: site.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def enablerlcompleter():
    """Enable default readline configuration on interactive prompts, by
    registering a sys.__interactivehook__.

    If the readline module can be imported, the hook will set the Tab key
    as completion key and register ~/.python_history as history file.
    This can be overriden in the sitecustomize or usercustomize module,
    or in a PYTHONSTARTUP file.
    """
    def register_readline():
        import atexit
        try:
            import readline
            import rlcompleter
        except ImportError:
            return

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file.
        readline_doc = getattr(readline, '__doc__', '')
        if readline_doc is not None and 'libedit' in readline_doc:
            readline.parse_and_bind('bind ^I rl_complete')
        else:
            readline.parse_and_bind('tab: complete')

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        if readline.get_current_history_length() == 0:
            # If no history was loaded, default to .python_history.
            # The guard is necessary to avoid doubling history size at
            # each interpreter exit when readline was already configured
            # through a PYTHONSTARTUP hook, see:
            # http://bugs.python.org/issue5845#msg198636
            history = os.path.join(os.path.expanduser('~'),
                                   '.python_history')
            try:
                readline.read_history_file(history)
            except IOError:
                pass
            atexit.register(readline.write_history_file, history)

    sys.__interactivehook__ = register_readline 
Example #19
Source File: site.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def enablerlcompleter():
    """Enable default readline configuration on interactive prompts, by
    registering a sys.__interactivehook__.

    If the readline module can be imported, the hook will set the Tab key
    as completion key and register ~/.python_history as history file.
    This can be overriden in the sitecustomize or usercustomize module,
    or in a PYTHONSTARTUP file.
    """
    def register_readline():
        import atexit
        try:
            import readline
            import rlcompleter
        except ImportError:
            return

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file.
        readline_doc = getattr(readline, '__doc__', '')
        if readline_doc is not None and 'libedit' in readline_doc:
            readline.parse_and_bind('bind ^I rl_complete')
        else:
            readline.parse_and_bind('tab: complete')

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        if readline.get_current_history_length() == 0:
            # If no history was loaded, default to .python_history.
            # The guard is necessary to avoid doubling history size at
            # each interpreter exit when readline was already configured
            # through a PYTHONSTARTUP hook, see:
            # http://bugs.python.org/issue5845#msg198636
            history = os.path.join(os.path.expanduser('~'),
                                   '.python_history')
            try:
                readline.read_history_file(history)
            except IOError:
                pass
            atexit.register(readline.write_history_file, history)

    sys.__interactivehook__ = register_readline 
Example #20
Source File: pysession.py    From pysession with MIT License 4 votes vote down vote up
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 
Example #21
Source File: pythonrc.py    From pythonrc with MIT License 4 votes vote down vote up
def init_readline(self):
        """Activates history and tab completion
        """
        # - mainly borrowed from site.enablerlcompleter() from py3.4+

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file.
        readline_doc = getattr(readline, '__doc__', '')
        if readline_doc is not None and 'libedit' in readline_doc:
            readline.parse_and_bind('bind ^I rl_complete')
        else:
            readline.parse_and_bind('tab: complete')

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        if readline.get_current_history_length() == 0:
            # If no history was loaded, default to .python_history.
            # The guard is necessary to avoid doubling history size at
            # each interpreter exit when readline was already configured
            # see: http://bugs.python.org/issue5845#msg198636
            try:
                readline.read_history_file(config['HISTFILE'])
            except IOError:
                pass
            atexit.register(readline.write_history_file,
                            config['HISTFILE'])
        readline.set_history_length(config['HISTSIZE'])

        # - replace default completer
        readline.set_completer(self.improved_rlcompleter())

        # - enable auto-indenting
        if config['AUTO_INDENT']:
            readline.set_pre_input_hook(self.auto_indent_hook)

        # - remove '/' and '~' from delimiters to help with path completion
        completer_delims = readline.get_completer_delims()
        completer_delims = completer_delims.replace('/', '')
        if config.get('COMPLETION_EXPANDS_TILDE'):
            completer_delims = completer_delims.replace('~', '')
        readline.set_completer_delims(completer_delims) 
Example #22
Source File: site.py    From deepWordBug with Apache License 2.0 4 votes vote down vote up
def enablerlcompleter():
    """Enable default readline configuration on interactive prompts, by
    registering a sys.__interactivehook__.
    If the readline module can be imported, the hook will set the Tab key
    as completion key and register ~/.python_history as history file.
    This can be overridden in the sitecustomize or usercustomize module,
    or in a PYTHONSTARTUP file.
    """

    def register_readline():
        import atexit

        try:
            import readline
            import rlcompleter
        except ImportError:
            return

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file.
        readline_doc = getattr(readline, "__doc__", "")
        if readline_doc is not None and "libedit" in readline_doc:
            readline.parse_and_bind("bind ^I rl_complete")
        else:
            readline.parse_and_bind("tab: complete")

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        if readline.get_current_history_length() == 0:
            # If no history was loaded, default to .python_history.
            # The guard is necessary to avoid doubling history size at
            # each interpreter exit when readline was already configured
            # through a PYTHONSTARTUP hook, see:
            # http://bugs.python.org/issue5845#msg198636
            history = os.path.join(os.path.expanduser("~"), ".python_history")
            try:
                readline.read_history_file(history)
            except OSError:
                pass

            def write_history():
                try:
                    readline.write_history_file(history)
                except (FileNotFoundError, PermissionError):
                    # home directory does not exist or is not writable
                    # https://bugs.python.org/issue19891
                    pass

            atexit.register(write_history)

    sys.__interactivehook__ = register_readline 
Example #23
Source File: site.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 4 votes vote down vote up
def enablerlcompleter():
    """Enable default readline configuration on interactive prompts, by
    registering a sys.__interactivehook__.

    If the readline module can be imported, the hook will set the Tab key
    as completion key and register ~/.python_history as history file.
    This can be overridden in the sitecustomize or usercustomize module,
    or in a PYTHONSTARTUP file.
    """
    def register_readline():
        import atexit
        try:
            import readline
            import rlcompleter
        except ImportError:
            return

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file.
        readline_doc = getattr(readline, '__doc__', '')
        if readline_doc is not None and 'libedit' in readline_doc:
            readline.parse_and_bind('bind ^I rl_complete')
        else:
            readline.parse_and_bind('tab: complete')

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        if readline.get_current_history_length() == 0:
            # If no history was loaded, default to .python_history.
            # The guard is necessary to avoid doubling history size at
            # each interpreter exit when readline was already configured
            # through a PYTHONSTARTUP hook, see:
            # http://bugs.python.org/issue5845#msg198636
            history = os.path.join(os.path.expanduser('~'),
                                   '.python_history')
            try:
                readline.read_history_file(history)
            except IOError:
                pass
            atexit.register(readline.write_history_file, history)

    sys.__interactivehook__ = register_readline 
Example #24
Source File: shell.py    From conary with Apache License 2.0 4 votes vote down vote up
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 
Example #25
Source File: isolate_readline_context.py    From phpsploit with GNU General Public License v3.0 4 votes vote down vote up
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 
Example #26
Source File: site.py    From coffeegrindsize with MIT License 4 votes vote down vote up
def enablerlcompleter():
    """Enable default readline configuration on interactive prompts, by
    registering a sys.__interactivehook__.
    If the readline module can be imported, the hook will set the Tab key
    as completion key and register ~/.python_history as history file.
    This can be overridden in the sitecustomize or usercustomize module,
    or in a PYTHONSTARTUP file.
    """

    def register_readline():
        import atexit

        try:
            import readline
            import rlcompleter
        except ImportError:
            return

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file.
        readline_doc = getattr(readline, "__doc__", "")
        if readline_doc is not None and "libedit" in readline_doc:
            readline.parse_and_bind("bind ^I rl_complete")
        else:
            readline.parse_and_bind("tab: complete")

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        if readline.get_current_history_length() == 0:
            # If no history was loaded, default to .python_history.
            # The guard is necessary to avoid doubling history size at
            # each interpreter exit when readline was already configured
            # through a PYTHONSTARTUP hook, see:
            # http://bugs.python.org/issue5845#msg198636
            history = os.path.join(os.path.expanduser("~"), ".python_history")
            try:
                readline.read_history_file(history)
            except OSError:
                pass

            def write_history():
                try:
                    readline.write_history_file(history)
                except (FileNotFoundError, PermissionError):
                    # home directory does not exist or is not writable
                    # https://bugs.python.org/issue19891
                    pass

            atexit.register(write_history)

    sys.__interactivehook__ = register_readline 
Example #27
Source File: isolate_io_context.py    From phpsploit with GNU General Public License v3.0 4 votes vote down vote up
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