Python readline.write_history_file() Examples

The following are 30 code examples of readline.write_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: interactive.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def save_history(self):
        if self.history_file_full_path is not None:
            global readline
            if readline is None:
                try:
                    import readline
                except ImportError:
                    return
            try:
                readline.write_history_file(self.history_file_full_path)
            except IOError:
                e = sys.exc_info()[1]
                warnings.warn("Cannot save history file, reason: %s" % str(e))

#------------------------------------------------------------------------------
# Main loop

    # Debugging loop. 
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: 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 #5
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 #6
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 #7
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 #8
Source File: consolecmd.py    From bacpypes with MIT License 6 votes vote down vote up
def postloop(self):
        """Take care of any unfinished business.
        Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
        """
        try:
            if readline:
                readline.write_history_file(sys.argv[0] + ".history")
        except Exception as err:
            if not isinstance(err, IOError):
                self.stdout.write("history error: %s\n" % err)

        # clean up command completion
        cmd.Cmd.postloop(self)

        if self.interactive:
            self.stdout.write("Exiting...\n")

        # tell the core we have stopped
        core.deferred(core.stop) 
Example #9
Source File: consolecmd.py    From bacpypes with MIT License 6 votes vote down vote up
def postloop(self):
        """Take care of any unfinished business.
        Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
        """
        try:
            if readline:
                readline.write_history_file(sys.argv[0] + ".history")
        except Exception as err:
            if not isinstance(err, IOError):
                self.stdout.write("history error: %s\n" % err)

        # clean up command completion
        cmd.Cmd.postloop(self)

        if self.interactive:
            self.stdout.write("Exiting...\n")

        # tell the core we have stopped
        core.deferred(core.stop) 
Example #10
Source File: interactive.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save_history(self):
        if self.history_file_full_path is not None:
            global readline
            if readline is None:
                try:
                    import readline
                except ImportError:
                    return
            try:
                readline.write_history_file(self.history_file_full_path)
            except IOError, e:
                warnings.warn("Cannot save history file, reason: %s" % str(e))

#------------------------------------------------------------------------------
# Main loop

    # Debugging loop. 
Example #11
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 #12
Source File: interactive.py    From filmkodi with Apache License 2.0 6 votes vote down vote up
def save_history(self):
        if self.history_file_full_path is not None:
            global readline
            if readline is None:
                try:
                    import readline
                except ImportError:
                    return
            try:
                readline.write_history_file(self.history_file_full_path)
            except IOError:
                e = sys.exc_info()[1]
                warnings.warn("Cannot save history file, reason: %s" % str(e))

#------------------------------------------------------------------------------
# Main loop

    # Debugging loop. 
Example #13
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 #14
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 #15
Source File: main.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def scapy_write_history_file(readline):
    if conf.histfile:
        try:
            readline.write_history_file(conf.histfile)
        except IOError,e:
            try:
                warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e))
                tmp = utils.get_temp_file(keep=True)
                readline.write_history_file(tmp)
                warning("Wrote history to [%s]" % tmp)
            except:
                warning("Cound not write history to [%s]. Discarded" % tmp) 
Example #16
Source File: smartconsole.py    From iOSSecAudit with GNU General Public License v3.0 5 votes vote down vote up
def save_history(self, histfile):
        readline.write_history_file(histfile) 
Example #17
Source File: shell.py    From conary with Apache License 2.0 5 votes vote down vote up
def save_history(self):
        if hasReadline and self._history_path:
            readline.set_history_length(1000)
            try:
                readline.write_history_file(self._history_path)
            except:
                pass 
Example #18
Source File: interactive.py    From rainbowstream with MIT License 5 votes vote down vote up
def save_history():
    """
    Save history to file
    """
    try:
        readline.write_history_file(c['HISTORY_FILENAME'])
    except:
        pass 
Example #19
Source File: main.py    From dash-hack with MIT License 5 votes vote down vote up
def scapy_write_history_file(readline):
    if conf.histfile:
        try:
            readline.write_history_file(conf.histfile)
        except IOError,e:
            try:
                warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e))
                tmp = utils.get_temp_file(keep=True)
                readline.write_history_file(tmp)
                warning("Wrote history to [%s]" % tmp)
            except:
                warning("Cound not write history to [%s]. Discarded" % tmp) 
Example #20
Source File: main.py    From dash-hack with MIT License 5 votes vote down vote up
def scapy_write_history_file(readline):
    if conf.histfile:
        try:
            readline.write_history_file(conf.histfile)
        except IOError,e:
            try:
                warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e))
                tmp = utils.get_temp_file(keep=True)
                readline.write_history_file(tmp)
                warning("Wrote history to [%s]" % tmp)
            except:
                warning("Cound not write history to [%s]. Discarded" % tmp) 
Example #21
Source File: main.py    From isip with MIT License 5 votes vote down vote up
def scapy_write_history_file(readline):
    if conf.histfile:
        try:
            readline.write_history_file(conf.histfile)
        except IOError,e:
            try:
                warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e))
                tmp = utils.get_temp_file(keep=True)
                readline.write_history_file(tmp)
                warning("Wrote history to [%s]" % tmp)
            except:
                warning("Cound not write history to [%s]. Discarded" % tmp) 
Example #22
Source File: main.py    From dash-hack with MIT License 5 votes vote down vote up
def scapy_write_history_file(readline):
    if conf.histfile:
        try:
            readline.write_history_file(conf.histfile)
        except IOError,e:
            try:
                warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e))
                tmp = utils.get_temp_file(keep=True)
                readline.write_history_file(tmp)
                warning("Wrote history to [%s]" % tmp)
            except:
                warning("Cound not write history to [%s]. Discarded" % tmp) 
Example #23
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 #24
Source File: console.py    From pappy-proxy with MIT License 5 votes vote down vote up
def save_histfile(self):
        # Write the command to the history file
        if self.histsize != 0:
            readline.set_history_length(self.histsize)
            readline.write_history_file('cmdhistory') 
Example #25
Source File: consolecmd.py    From bacpypes with MIT License 5 votes vote down vote up
def postloop(self):
        """Take care of any unfinished business.
        Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
        """
        try:
            if readline:
                readline.write_history_file(sys.argv[0] + ".history")
        except Exception, err:
            if not isinstance(err, IOError):
                self.stdout.write("history error: %s\n" % err)

        # clean up command completion 
Example #26
Source File: interact.py    From topology with Apache License 2.0 5 votes vote down vote up
def interact(mgr):
    """
    Shell setup function.

    This function will setup the library, create the default namespace with
    shell symbols, setup the history file, the autocompleter and launch a shell
    session.
    """
    print('Engine nodes available for communication:')
    print('    {}'.format(', '.join(mgr.nodes.keys())))

    # Create and populate shell namespace
    ns = {
        'topology': mgr
    }
    for key, enode in mgr.nodes.items():
        ns[key] = enode

    # Configure readline, history and autocompleter
    import readline

    histfile = join(expanduser('~'), '.topology_history')
    if isfile(histfile):
        try:
            readline.read_history_file(histfile)
        except IOError:
            log.error(format_exc())
    register(readline.write_history_file, histfile)

    completer = NamespaceCompleter(ns)
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')

    # Python's Interactive
    from code import interact as pyinteract
    pyinteract('', None, ns) 
Example #27
Source File: pncload.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_history(self, histfile):
        """
        Write history from session to disk
        """
        import readline
        readline.write_history_file(histfile) 
Example #28
Source File: compinit.py    From collection with MIT License 5 votes vote down vote up
def __completion_init():
	try:
		import readline
		import rlcompleter
		import atexit
		import os
		import sys
	except ImportError:
		return -1
	try:
		readline.parse_and_bind('tab: complete')
	except:
		return -2
	local = os.path.expanduser('~/.local')
	if not os.path.exists(local):
		try:
			os.mkdir(local)
		except:
			return -2
	if not os.path.exists(local + '/var'):
		try:
			os.mkdir(local + '/var')
		except:
			return -3
	history = local + '/var/python%d_hist'%sys.version_info[0]
	try:
		readline.read_history_file(history)
	except:
		pass
	atexit.register(readline.write_history_file, history)
	return 0 
Example #29
Source File: terminal.py    From weevely3 with GNU General Public License v3.0 5 votes vote down vote up
def _load_history(self):
        """Load history file and register dump on exit."""

        # Create a file without truncating it in case it exists.
        open(config.history_path, 'a').close()

        readline.set_history_length(100)
        try:
            readline.read_history_file(config.history_path)
        except IOError:
            pass
        atexit.register(readline.write_history_file,
            config.history_path) 
Example #30
Source File: cli.py    From opensips-cli with GNU General Public License v3.0 5 votes vote down vote up
def history_write(self):
        """
        save history file
        """
        history_file = cfg.get('history_file')
        logger.debug("saving history in {}".format(history_file))
        os.makedirs(os.path.expanduser(os.path.dirname(history_file)), exist_ok=True)
        try:
            readline.write_history_file(os.path.expanduser(history_file))
        except PermissionError:
            logger.warning("failed to write CLI history to {} " +
                            "(no permission)".format(
                history_file))