Python readline.read_history_file() Examples

The following are 30 code examples of readline.read_history_file(). 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: pundle.py    From pundler with BSD 2-Clause "Simplified" License 9 votes vote down vote up
def run_console(glob):
    import readline
    import rlcompleter
    import atexit
    import code

    history_path = os.path.expanduser("~/.python_history")

    def save_history(history_path=history_path):
        readline.write_history_file(history_path)
    if os.path.exists(history_path):
        readline.read_history_file(history_path)

    atexit.register(save_history)

    readline.set_completer(rlcompleter.Completer(glob).complete)
    readline.parse_and_bind("tab: complete")
    code.InteractiveConsole(locals=glob).interact() 
Example #2
Source File: shell.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def enable_autocomplete_and_history(adir,env):
    try:
        import rlcompleter
        import atexit
        import readline
    except ImportError:
        pass
    else:
        readline.parse_and_bind("bind ^I rl_complete"
                                if sys.platform == 'darwin'
                                else "tab: complete")
        history_file = os.path.join(adir,'.pythonhistory')
        try:
            readline.read_history_file(history_file)
        except IOError:
            open(history_file, 'a').close()
        atexit.register(readline.write_history_file, history_file)
        readline.set_completer(rlcompleter.Completer(env).complete) 
Example #3
Source File: cli.py    From clonedigger with GNU General Public License v3.0 6 votes vote down vote up
def init_readline(complete_method, histfile=None):
    """init the readline library if available"""
    try:
        import readline
        readline.parse_and_bind("tab: complete")
        readline.set_completer(complete_method)
        string = readline.get_completer_delims().replace(':', '')
        readline.set_completer_delims(string)
        if histfile is not None:
            try:
                readline.read_history_file(histfile)
            except IOError:
                pass
            import atexit
            atexit.register(readline.write_history_file, histfile)
    except:
        print('readline si not available :-(') 
Example #4
Source File: smartconsole.py    From iOSSecAudit with GNU General Public License v3.0 6 votes vote down vote up
def init_history(self, histfile):
    
        #readline.parse_and_bind("bind ^I rl_complete")
        
        # Register our completer function
        readline.set_completer(SimpleCompleter(G.cmmands.keys()).complete)
        
        
        #readline.set_completer(TabCompleter().complete)
        ### Add autocompletion
        if 'libedit' in readline.__doc__:
            readline.parse_and_bind("bind -e")
            readline.parse_and_bind("bind '\t' rl_complete")
        else:
            readline.parse_and_bind("tab: complete")
        
        # Use the tab key for completion
        #readline.parse_and_bind('tab: complete')
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(histfile)
            except:
                pass
            
            atexit.register(self.save_history, histfile) 
Example #5
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 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") 
Example #6
Source File: interactive.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_history(self):
        global readline
        if readline is None:
            try:
                import readline
            except ImportError:
                return
        if self.history_file_full_path is None:
            folder = os.environ.get('USERPROFILE', '')
            if not folder:
                folder = os.environ.get('HOME', '')
            if not folder:
                folder = os.path.split(sys.argv[0])[1]
            if not folder:
                folder = os.path.curdir
            self.history_file_full_path = os.path.join(folder,
                                                       self.history_file)
        try:
            if os.path.exists(self.history_file_full_path):
                readline.read_history_file(self.history_file_full_path)
        except IOError, e:
            warnings.warn("Cannot load history file, reason: %s" % str(e)) 
Example #7
Source File: interactive.py    From filmkodi with Apache License 2.0 6 votes vote down vote up
def load_history(self):
        global readline
        if readline is None:
            try:
                import readline
            except ImportError:
                return
        if self.history_file_full_path is None:
            folder = os.environ.get('USERPROFILE', '')
            if not folder:
                folder = os.environ.get('HOME', '')
            if not folder:
                folder = os.path.split(sys.argv[0])[1]
            if not folder:
                folder = os.path.curdir
            self.history_file_full_path = os.path.join(folder,
                                                       self.history_file)
        try:
            if os.path.exists(self.history_file_full_path):
                readline.read_history_file(self.history_file_full_path)
        except IOError:
            e = sys.exc_info()[1]
            warnings.warn("Cannot load history file, reason: %s" % str(e)) 
Example #8
Source File: utils.py    From QRLJacking with GNU General Public License v3.0 6 votes vote down vote up
def Input_completer(keywords):
    completer = MyCompleter(keywords)
    readline.set_completer(completer.complete)
    if "libedit" in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind('tab: complete')
        #readline.parse_and_bind('"\\e[A": complete') # Up arrow
    readline.parse_and_bind("set colored-completion-prefix on")
    readline.parse_and_bind("set show-all-if-unmodified on")
    readline.parse_and_bind("set horizontal-scroll-mode on")
    if os.path.exists(history_file):
        readline.read_history_file(history_file)
        readline.set_history_length(20)
    readline.set_completer_delims(' ')
    atexit.register(save_history) 
Example #9
Source File: BaseInterpreter.py    From Industrial-Security-Auditing-Framework with GNU General Public License v3.0 6 votes vote down vote up
def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete") 
Example #10
Source File: repl.py    From sdb with Apache License 2.0 6 votes vote down vote up
def enable_history(self, history_file: str) -> None:
        self.histfile = os.path.expanduser(history_file)
        try:
            readline.read_history_file(self.histfile)
        except FileNotFoundError:
            pass
        except PermissionError:
            self.histfile = ""
            print(
                f"Warning: You don't have permissions to read {history_file} and\n"
                "         the command history of this session won't be saved.\n"
                "         Either change this file's permissions, recreate it,\n"
                "         or use an alternate path with the SDB_HISTORY_FILE\n"
                "         environment variable.")
            return
        readline.set_history_length(1000)
        atexit.register(readline.write_history_file, self.histfile) 
Example #11
Source File: main.py    From frick with MIT License 6 votes vote down vote up
def start(self):
        self.cmd_manager.init()
        log('%s started - GL HF!' % Color.colorify('frick', 'green highligh'))

        readline.parse_and_bind('tab: complete')
        hist = os.path.join(os.environ['HOME'], '.frick_history')

        try:
            readline.read_history_file(hist)
        except IOError:
            pass
        atexit.register(readline.write_history_file, hist)

        while True:
            inp = six.moves.input().strip()
            if len(inp) > 0:
                self.cmd_manager.handle_command(inp) 
Example #12
Source File: interpreter.py    From isf with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete") 
Example #13
Source File: cli.py    From opensips-cli with GNU General Public License v3.0 6 votes vote down vote up
def preloop(self):
        """
        preload a history file
        """
        history_file = cfg.get('history_file')
        logger.debug("using history file {}".format(history_file))
        try:
            readline.read_history_file(os.path.expanduser(history_file))
        except PermissionError:
            logger.warning("failed to read CLI history from {} " +
                            "(no permission)".format(
                history_file))
        except FileNotFoundError:
            pass

        readline.set_history_length(int(cfg.get('history_file_size')))
        if not self.registered_atexit:
            atexit.register(self.history_write) 
Example #14
Source File: interactive.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def load_history(self):
        global readline
        if readline is None:
            try:
                import readline
            except ImportError:
                return
        if self.history_file_full_path is None:
            folder = os.environ.get('USERPROFILE', '')
            if not folder:
                folder = os.environ.get('HOME', '')
            if not folder:
                folder = os.path.split(sys.argv[0])[1]
            if not folder:
                folder = os.path.curdir
            self.history_file_full_path = os.path.join(folder,
                                                       self.history_file)
        try:
            if os.path.exists(self.history_file_full_path):
                readline.read_history_file(self.history_file_full_path)
        except IOError:
            e = sys.exc_info()[1]
            warnings.warn("Cannot load history file, reason: %s" % str(e)) 
Example #15
Source File: shell.py    From web_develop with GNU General Public License v3.0 6 votes vote down vote up
def hook_readline_hist():
    try:
        import readline
    except ImportError:
        return

    histfile = os.environ['HOME'] + '/.web_develop_history'  # 定义一个存储历史记录的文件地址
    readline.parse_and_bind('tab: complete')
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass  # It doesn't exist yet.

    def savehist():
        try:
            readline.write_history_file(histfile)
        except:
            print 'Unable to save Python command history'
    atexit.register(savehist) 
Example #16
Source File: test_readline.py    From android_universal with MIT License 6 votes vote down vote up
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") 
Example #17
Source File: defs.py    From hadrian with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        """Create the main mode.

        If titus.inspector.defs.CONFIG_DIRECTORY_EXISTS is ``True``, get the readline history file from the user's titus.inspector.defs.CONFIG_DIRECTORY.
        """

        if CONFIG_DIRECTORY_EXISTS:
            self.historyPath = os.path.join(os.path.expanduser(CONFIG_DIRECTORY), self.historyFileName)
            if not os.path.exists(self.historyPath):
                open(self.historyPath, "w").close()

            self.active = True
            self.tabCompleter = TabCompleter(self)
            readline.read_history_file(self.historyPath)
            readline.set_completer(self.tabCompleter.complete)

            def writehistory():
                if self.active:
                    readline.write_history_file(self.historyPath)
            atexit.register(writehistory) 
Example #18
Source File: shell.py    From canari3 with GNU General Public License v3.0 5 votes vote down vote up
def init_history(history_file):
        try:
            import readline
            readline.parse_and_bind('tab: complete')
            if hasattr(readline, "read_history_file"):
                try:
                    readline.read_history_file(history_file)
                except IOError:
                    pass
                register(lambda h: readline.write_history_file(h), history_file)
        except ImportError:
            pass 
Example #19
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_history_size(self):
        history_size = 10
        with temp_dir() as test_dir:
            inputrc = os.path.join(test_dir, "inputrc")
            with open(inputrc, "wb") as f:
                f.write(b"set history-size %d\n" % history_size)

            history_file = os.path.join(test_dir, "history")
            with open(history_file, "wb") as f:
                # history_size * 2 items crashes readline
                data = b"".join(b"item %d\n" % i
                                for i in range(history_size * 2))
                f.write(data)

            script = """
import os
import readline

history_file = os.environ["HISTORY_FILE"]
readline.read_history_file(history_file)
input()
readline.write_history_file(history_file)
"""

            env = dict(os.environ)
            env["INPUTRC"] = inputrc
            env["HISTORY_FILE"] = history_file

            run_pty(script, input=b"last input\r", env=env)

            with open(history_file, "rb") as f:
                lines = f.readlines()
            self.assertEqual(len(lines), history_size)
            self.assertEqual(lines[-1].strip(), b"last input") 
Example #20
Source File: PupyCmd.py    From backdoorme with MIT License 5 votes vote down vote up
def init_readline(self):
		try:
			readline.read_history_file(".pupy_history")
		except Exception:
			pass
		self.init_completer() 
Example #21
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 #22
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 #23
Source File: test_readline.py    From android_universal with MIT License 5 votes vote down vote up
def test_history_size(self):
        history_size = 10
        with temp_dir() as test_dir:
            inputrc = os.path.join(test_dir, "inputrc")
            with open(inputrc, "wb") as f:
                f.write(b"set history-size %d\n" % history_size)

            history_file = os.path.join(test_dir, "history")
            with open(history_file, "wb") as f:
                # history_size * 2 items crashes readline
                data = b"".join(b"item %d\n" % i
                                for i in range(history_size * 2))
                f.write(data)

            script = """
import os
import readline

history_file = os.environ["HISTORY_FILE"]
readline.read_history_file(history_file)
input()
readline.write_history_file(history_file)
"""

            env = dict(os.environ)
            env["INPUTRC"] = inputrc
            env["HISTORY_FILE"] = history_file

            run_pty(script, input=b"last input\r", env=env)

            with open(history_file, "rb") as f:
                lines = f.readlines()
            self.assertEqual(len(lines), history_size)
            self.assertEqual(lines[-1].strip(), b"last input") 
Example #24
Source File: base.py    From isip with MIT License 5 votes vote down vote up
def preloop(self):
        """
        Initialization before prompting user for commands.
        Despite the claims in the Cmd documentation, Cmd.preloop() is not a stub.
        """
        cmd.Cmd.preloop(self)

        self._hist = []
        self._locals = defaultdict(set)
        self._globals = defaultdict(set)

        try:
            readline.read_history_file(self.hist_file)
        except IOError:
            pass 
Example #25
Source File: cmdline.py    From compoundpi with GNU General Public License v2.0 5 votes vote down vote up
def preloop(self):
        if self.color_prompt:
            self.prompt = COLOR_BOLD + COLOR_GREEN + self.prompt + COLOR_RESET
        if self.history_file and os.path.exists(self.history_file):
            readline.read_history_file(self.history_file)
        # Replace the _CONSOLE logging handler with something that calls pprint
        logging.getLogger().addHandler(self.logging_handler)
        logging.getLogger().removeHandler(_CONSOLE)
        # Replace warnings.showwarning with something that calls pprint
        self._showwarning = warnings.showwarning
        warnings.showwarning = self.showwarning 
Example #26
Source File: shell.py    From conary with Apache License 2.0 5 votes vote down vote up
def read_history(self):
        if hasReadline and self._history_path:
            try:
                readline.read_history_file(self._history_path)
            except:
                pass 
Example #27
Source File: console.py    From pappy-proxy with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        # the \x01/\x02 are to make the prompt behave properly with the readline library
        self.prompt = 'pappy\x01' + Colors.YELLOW + '\x02> \x01' + Colors.ENDC + '\x02'
        self.debug = True
        self.histsize = 0
        if 'histsize' in kwargs:
            self.histsize = kwargs['histsize']
            del kwargs['histsize']
        if 'client' not in kwargs:
            raise Exception("client argument is required")
        self.client = kwargs['client']
        self.client.console = self
        del kwargs['client']

        self._cmds = {}
        self._aliases = {}

        atexit.register(self.save_histfile)
        readline.set_history_length(self.histsize)
        if os.path.exists('cmdhistory'):
            if self.histsize != 0:
                readline.read_history_file('cmdhistory')
            else:
                os.remove('cmdhistory')

        cmd2.Cmd.__init__(self, *args, **kwargs) 
Example #28
Source File: consolecmd.py    From bacpypes with MIT License 5 votes vote down vote up
def preloop(self):
        """Initialization before prompting user for commands.
        Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
        """
        cmd.Cmd.preloop(self)   ## sets up command completion

        try:
            if readline:
                readline.read_history_file(sys.argv[0] + ".history")
        except Exception, err:
            if not isinstance(err, IOError):
                self.stdout.write("history error: %s\n" % err) 
Example #29
Source File: consolecmd.py    From bacpypes with MIT License 5 votes vote down vote up
def preloop(self):
        """Initialization before prompting user for commands.
        Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
        """
        cmd.Cmd.preloop(self)   ## sets up command completion

        try:
            if readline:
                readline.read_history_file(sys.argv[0] + ".history")
        except Exception as err:
            if not isinstance(err, IOError):
                self.stdout.write("history error: %s\n" % err) 
Example #30
Source File: consolecmd.py    From bacpypes with MIT License 5 votes vote down vote up
def preloop(self):
        """Initialization before prompting user for commands.
        Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
        """
        cmd.Cmd.preloop(self)   ## sets up command completion

        try:
            if readline:
                readline.read_history_file(sys.argv[0] + ".history")
        except Exception as err:
            if not isinstance(err, IOError):
                self.stdout.write("history error: %s\n" % err)