Python readline.set_history_length() Examples

The following are 28 code examples of readline.set_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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: main.py    From polysh with GNU General Public License v2.0 5 votes vote down vote up
def save_history(histfile: str) -> None:
    readline.set_history_length(1000)
    readline.write_history_file(histfile) 
Example #8
Source File: webshellConnector.py    From Blade with GNU General Public License v2.0 5 votes vote down vote up
def saveHistory(self):
        readline.set_history_length(1000)
        readline.write_history_file(self.HISTORY_FILE)

    # Get OS type of the host
    # param: none
    # return: osType 
Example #9
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 #10
Source File: athena_cli.py    From athena-cli with Apache License 2.0 5 votes vote down vote up
def init_history(self):
        try:
            readline.read_history_file(self.hist_file)
            readline.set_history_length(HISTORY_FILE_SIZE)
            readline.write_history_file(self.hist_file)
        except IOError:
            readline.write_history_file(self.hist_file)

        atexit.register(self.save_history) 
Example #11
Source File: cmdline.py    From compoundpi with GNU General Public License v2.0 5 votes vote down vote up
def postloop(self):
        readline.set_history_length(self.history_size)
        readline.write_history_file(self.history_file)
        # Restore the warnings.showwarning handler
        warnings.showwarning = self._showwarning
        # Restore the _CONSOLE handler
        logging.getLogger().addHandler(_CONSOLE)
        logging.getLogger().removeHandler(self.logging_handler) 
Example #12
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 #13
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 #14
Source File: pncload.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def init_history(self, histfile):
        """
        Prepare history for use from histfile (typically last session)
        """
        import readline
        readline.parse_and_bind("tab: complete")
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(histfile)
                readline.set_history_length(1000)
            except IOError:
                pass
            atexit.register(self.save_history, histfile) 
Example #15
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 #16
Source File: recipe-578098.py    From code with MIT License 5 votes vote down vote up
def autocomplete():
        import atexit
        import os
        import readline
        import rlcompleter

        def save_history():
            readline.set_history_length(10000)
            readline.write_history_file(history_path)

        history_path = os.path.expanduser("~/.pyhistory")
        if os.path.exists(history_path):
            readline.read_history_file(history_path)
        atexit.register(save_history)
        readline.parse_and_bind('tab: complete') 
Example #17
Source File: shell.py    From BoomER with GNU General Public License v3.0 5 votes vote down vote up
def initial(self):
        self.completer = MyCompleter.getInstance(self._options_start.keys(), self)
        readline.set_history_length(50)  # max 50
        readline.set_completer_delims(' \t\n;')  # override the delims (we want /)
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.completer.complete)
        self.open_sessions = Session.getInstance() 
Example #18
Source File: cmd_line.py    From pyss3 with MIT License 5 votes vote down vote up
def do_exit(self, args=''):
        """Quit the program."""
        print("Bye")
        if readline:
            readline.set_history_length(HISTFILE_SIZE)
            try:
                readline.write_history_file(HISTFILE)
            except IOError:
                pass
        raise SystemExit 
Example #19
Source File: interactive.py    From scrounger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def postloop(self):
        _Cmd.postloop(self)   ## Clean up command completion

        try:
            readline.set_history_length(_MAX_HISTORY)
            readline.write_history_file(_HISTORY_FILE)
        except:
            # readline is returning Exception for some reason
            pass 
Example #20
Source File: threatshell.py    From threatshell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, args):

        Cmd.__init__(self)

        self.args = args
        self.threat_q = ThreatQ(config)
        self.geo_tools = GeoTools(config)
        self.infoblox = Infoblox(config)
        self.passive_total = PassiveTotal(config)
        self.riq = RiskIQ(config)
        self.novetta = Novetta(config)
        self.config_manager = ConfigManager(config)
        self.ss = ShadowServer()
        self.cymru = Cymru()
        self.opendns = OpenDNS_API(config)
        self.umbrella = Umbrella(config)
        self.tx = ThreatExchange(config)

        self.module_map = {}
        for entry in dir(self):
            entry = getattr(self, entry)
            if hasattr(entry, "__module__"):
                if "commands" in entry.__module__:
                    self.module_map[entry.__module__] = entry

        try:
            readline.read_history_file(self.history_file)
        except IOError:
            pass

        readline.set_history_length(300)  # TODO: Maybe put this in a config 
Example #21
Source File: riposte.py    From riposte with MIT License 5 votes vote down vote up
def _setup_history(history_file: Path, history_length: int) -> None:
        if not history_file.exists():
            with open(history_file, "a+") as history:
                if is_libedit():
                    history.write("_HiStOrY_V2_\n\n")

        readline.read_history_file(str(history_file))
        readline.set_history_length(history_length)
        atexit.register(readline.write_history_file, str(history_file)) 
Example #22
Source File: shell.py    From alma-slipsomat with MIT License 5 votes vote down vote up
def execute(self, fn, *args, **kwargs):
        """Execute the function and handle any exceptions."""
        if readline is not None:
            readline.set_history_length(10000)
            readline.write_history_file(histfile)
        try:
            fn(*args, **kwargs)
        except Exception as e:
            self.handle_exception(e) 
Example #23
Source File: interface.py    From phpsploit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.nocmd = None
        self.last_exception = None
        super().__init__()
        try:
            import readline
            readline.set_history_length(session.Hist.MAX_SIZE)
            readline.set_completer_delims(READLINE_COMPLETER_DELIMS)
        except ImportError:
            pass 
Example #24
Source File: console.py    From plasma with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, con):
        readline.set_completer_delims(' \t\n;')
        readline.set_history_length(100)
        readline.set_completer(self.complete)
        readline.parse_and_bind("tab: complete")
        self.con = con 
Example #25
Source File: framework.py    From Exploit-Framework with GNU General Public License v3.0 5 votes vote down vote up
def setup():
    history_file = "./.history"
    if not os.path.exists(history_file):
        open(history_file, 'a+').close()

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

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

    readline.set_completer(complete)
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete") 
Example #26
Source File: libra_shell.py    From libra-client with MIT License 5 votes vote down vote up
def main():
    signal.signal(signal.SIGTERM, handler)
    signal.signal(signal.SIGINT, handler)
    # signal.signal(signal.SIGTSTP, handler)
    if os.name == 'posix':
        readline.set_history_length(1000)
    parser = get_parser()
    libra_args = parser.parse_args(sys.argv[1:])
    try:
        run_shell(libra_args)
    except Exception as err:
        report_error("some error occured", err, libra_args.verbose) 
Example #27
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 #28
Source File: cli.py    From zstack-utility with Apache License 2.0 4 votes vote down vote up
def __init__(self, options):
        """
        Constructor
        """
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)
        readline.set_completion_display_matches_hook(self.completer_print)
        try:
            readline.read_history_file(CLI_HISTORY)
        except IOError:
            pass
        readline.set_history_length(CLI_MAX_CMD_HISTORY)

        if not os.path.isdir(CLI_RESULT_HISTORY_FOLDER):

            linux.rm_dir_force(os.path.dirname(CLI_RESULT_HISTORY_FOLDER))
            os.system('mkdir -p %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))

        try:
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
        except:
            linux.rm_dir_force(CLI_RESULT_HISTORY_KEY)
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
            print "\nRead history file: %s error. Has recreate it.\n" % CLI_RESULT_HISTORY_KEY

        self.start_key = 'start_key'
        self.last_key = 'last_key'
        self.cli_cmd_func = {'help': self.show_help,
                             'history': self.show_help,
                             'more': self.show_more,
                             'quit': sys.exit,
                             'exit': sys.exit,
                             'save': self.save_json_to_file}
        self.cli_cmd = self.cli_cmd_func.keys()

        self.raw_words_db = self._parse_api_name(inventory.api_names)
        self.words_db = list(self.raw_words_db)
        self.words_db.extend(self.cli_cmd)
        self.words = list(self.words_db)
        self.is_cmd = False
        self.curr_pattern = None
        self.matching_words = None
        self.api_class_params = {}
        self.build_api_parameters()
        self.api = None
        self.account_name = None
        self.user_name = None
        self.session_uuid = None
        if os.path.exists(SESSION_FILE):
            try:
                with open(SESSION_FILE, 'r') as session_file_reader:
                    self.session_uuid = session_file_reader.readline().rstrip()
                    self.account_name = session_file_reader.readline().rstrip()
                    self.user_name = session_file_reader.readline().rstrip()
            except EOFError:
                pass

        self.hostname = options.host
        self.port = options.port
        self.no_secure = options.no_secure
        self.api = api.Api(host=self.hostname, port=self.port)