当前位置: 首页>>代码示例>>Python>>正文


Python readline.get_history_item函数代码示例

本文整理汇总了Python中readline.get_history_item函数的典型用法代码示例。如果您正苦于以下问题:Python get_history_item函数的具体用法?Python get_history_item怎么用?Python get_history_item使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_history_item函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: do_history

 def do_history(self, args):
     """
     Prints cloudmonkey history
     """
     if self.pipe_runner("history " + args):
         return
     startIdx = 1
     endIdx = readline.get_current_history_length()
     numLen = len(str(endIdx))
     historyArg = args.split(' ')[0]
     if historyArg.isdigit():
         startIdx = endIdx - long(historyArg)
         if startIdx < 1:
             startIdx = 1
     elif historyArg == "clear" or historyArg == "c":
         readline.clear_history()
         print "CloudMonkey history cleared"
         return
     elif len(historyArg) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit():
         command = readline.get_history_item(long(historyArg[1:]))
         readline.set_startup_hook(lambda: readline.insert_text(command))
         self.hook_count = 1
         return
     for idx in xrange(startIdx, endIdx):
         self.monkeyprint("%s %s" % (str(idx).rjust(numLen),
                                     readline.get_history_item(idx)))
开发者ID:waegemae,项目名称:cloudstack-cloudmonkey,代码行数:26,代码来源:cloudmonkey.py

示例2: history

    def history(start=None, end=None, lines=30,
                   number=False):
        """
        Display the history starting from entry 'start' to
        entry 'end'. Only available on platforms where the
        readline module can be imported.

        History starts from 0 and goes to a large number.
        The history file is $ZENHOME/.pyhistory by default.

        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        @parameter number: show the line numbers?
        @type number: boolean
        """
        if readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                if number:
                    print i, readline.get_history_item(i)
                else:
                    print readline.get_history_item(i)
开发者ID:zenoss,项目名称:zenoss-prodbin,代码行数:32,代码来源:zendmd.py

示例3: main

def main():
	prevrun = []
	warning = 0
	readline.parse_and_bind('tab: complete') # Enable local file tab completion and history
	#readline.read_history_file(history.his)
	# Need to initialize history file here TODO

	while True:
		try:
			dir = os.getcwd()
			input = raw_input('{} >> '.format(dir)) # Print >>, take user input (blocking)
			args = shlex.split(input) # Use shell lexer module to parse input into list of strings
			if input[0][0] == '!':
				if int(input[1][0]) > int(readline.get_current_history_length()):
					continue

				if readline.get_history_item(int(input[1][0])) is not None:
					args = shlex.split(readline.get_history_item(int(input[1][0])))

				if int(input[1][0]) == 0:
					args = prevrun
	
			run = builtins.get(args[0], builtin_exec) # Store relevant function into run variable (builtin_exec being default) 
			retVal = run(args) # Execute function stored in run with arguments args, storing the return value in retVal
			prevrun = args
			if warning > 0:
				warning = warning - 1 # This is a bit silly
			builtin_check_children()

		
		except KeyboardInterrupt: # Can use Finally to run commands regardless, or else to run things when no exception
			print "\r\nCaught interrupt signal! Killing any child processes..."
			builtin_kill_children()
			continue

		except EOFError:
			if len(children) > 0 and warning < 1:
				warning = warning + 3 # Two commands of leeway before next warning
				print "\r\nWarning: this shell still has child processes active. Pressing ^D again will kill them."
				continue
			builtin_kill_children()
			print "\r\nLogout"
			exit()
		
		except ValueError:
			print "Unable to parse command. Do you have a non-paired delimiter? Think (), [], '', or \"\""

		except OSError:
			print "Received an OS Error. Does the file or command you're looking for exist, or are you running out of memory?"
			#traceback.print_exc()
		
		except Exception:
			print "Error: I'm unsure of how to parse/execute the previous input. Common reasons for this are multiple redirects"
			print "on the same line, commands that don't syntactically make sense, or attempting to reach files that don't exist."
			print "Nothing but whitespace will also trigger this error."
			print "Additionally, I caught the following exception:"
			traceback.print_exc()
开发者ID:ElBaha,项目名称:Bahash,代码行数:57,代码来源:main.py

示例4: history

def history(history_id=None):
    if history_id is None:
        for i in range(readline.get_current_history_length()):
            print( str(i+1) + ': ' + readline.get_history_item(i+1) ) 
        return None

    else:

#        print( str(history_id ) + ': ' + readline.get_history_item(history_id) ) 
        return readline.get_history_item(history_id)
开发者ID:tongelja,项目名称:python_std,代码行数:10,代码来源:cmdtools.py

示例5: compact_history

def compact_history():
    if hasattr(readline, "replace_history_item"):
        unique_history = utils.unique_list()
        for index in reversed(list(range(1, readline.get_current_history_length()))):
            hist_item = readline.get_history_item(index)
            if hist_item:  # some history items are None (usually at index 0)
                unique_history.append(readline.get_history_item(index))
        unique_history.reverse()
        for index in range(len(unique_history)):
            readline.replace_history_item(index + 1, unique_history[index])
        for index in reversed(list(range(len(unique_history) + 1, readline.get_current_history_length()))):
            readline.remove_history_item(index)
开发者ID:wavesaudio,项目名称:instl,代码行数:12,代码来源:instlInstanceBase_interactive.py

示例6: __getitem__

 def __getitem__(self, index):
     '''
     Get a single event at ``index`` or a :class:`slice` of events.
     '''
     if isinstance(index, slice):
         start = self.normalize_index(index.start or 0)
         stop = self.normalize_index((index.stop or self.__len__())-1)
         step = index.step or 1
         return [readline.get_history_item(i) for i in range(start, stop+1, step)]
     else:
         index = self.normalize_index(index)
         return readline.get_history_item(index)
开发者ID:jeinstos,项目名称:pypsi,代码行数:12,代码来源:history.py

示例7: history

 def history(self, argv):
     """history [<index>]
 Display the current readline history buffer."""
     if not readline:
         self._print("The readline library is not available.")
         return
     if len(argv) > 1:
         idx = int(argv[1])
         self._print(readline.get_history_item(idx))
     else:
         for i in range(readline.get_current_history_length()):
             self._print(readline.get_history_item(i))
开发者ID:kdart,项目名称:pycopia3,代码行数:12,代码来源:CLI.py

示例8: save

def save():
    """save the readline history since last call to mark()"""
    end = readline.get_current_history_length() - 1
    session = []
    item = readline.get_history_item(end)
    while item != _marker:
        session.insert(0, item+"\n")
        end -= 1
        item = readline.get_history_item(end)
        
    file(_session_file, 'w').writelines(session)
    print >> sys.stderr, "saved session to", _session_file
开发者ID:nickzuck007,项目名称:python-bits,代码行数:12,代码来源:save_session.py

示例9: hist

def hist():
    """Fetches command line history. Returns dict of all lines."""
    history_dict = {}
    # create history_list
    for i in range(readline.get_current_history_length()):
        history_dict[i+1] = (readline.get_history_item(i+1))
    return history_dict
开发者ID:ztaira14,项目名称:myhistory,代码行数:7,代码来源:myhistory.py

示例10: run

    def run(self):

        # Preserve existing history
        if self.preserve_history:
            old_history = [readline.get_history_item(index) for index in xrange(readline.get_current_history_length())]
            readline.clear_history()
            map(readline.add_history, self.history)

        readline.set_completer(self.complete)
        readline.parse_and_bind("bind ^I rl_complete")

        while True:
            cmdline = raw_input("%s > " % (self.prefix,))
            self.last_wd_complete = ("", ())
            if not cmdline:
                continue

            # Try to dispatch command
            try:
                self.execute(cmdline)
            except SystemExit, e:
                print "Exiting shell: %s" % (e.code,)
                break
            except UnknownCommand, e:
                print "Command '%s' unknown." % (e,)
开发者ID:muelli,项目名称:CalDAVClientLibrary,代码行数:25,代码来源:baseshell.py

示例11: __history_try_search

 def __history_try_search(cls, text):
     history_range = range(readline.get_current_history_length(), 1, -1)
     for i in history_range:
         item = readline.get_history_item(i)
         if item.startswith(text):
             return item
     return ''
开发者ID:gstoeckel,项目名称:katello,代码行数:7,代码来源:shell.py

示例12: remote_log_history

def remote_log_history():
    import readline
    from time import time
    import requests
    import os
    import json
    import base64
    cnt = readline.get_current_history_length()
    for i in xrange(cnt):
        cmd = readline.get_history_item(i + 1)
        data = {}
        data['ts'] = time()
        data['cmd'] = base64.b64encode(cmd.encode('ascii'))
        data['optout'] = None
        if 'STATSOPTOUT' in os.environ:
            data['optout'] = os.environ['STATSOPTOUT']
        data['src'] = {}
        data['src']['user'] = os.environ['USER']
        if 'SESSIP' in os.environ:
            data['src']['ip'] = os.environ['SESSIP']
        pid = os.getpid()
        ppid = os.getppid()
        sessid = 'SESSID'
        if 'SESSID' in os.environ:
            sessid = os.environ['SESSID']
        data['src']['session'] = '%s.%s.%s.py' % (pid, ppid, sessid)
        url = 'http://ctf.local:9999/cmd'
        # print('request: %s' % json.dumps(data))
        try:
            requests.post(url, data=json.dumps(data), timeout=2.0)
        except:  # ConnectionError, HTTPError, Timeout, TooManyRedirects
            pass
开发者ID:rfarley3,项目名称:bash-recorder,代码行数:32,代码来源:pystartup.py

示例13: builtin_history

def builtin_history(args):
	print "\033[2J\033[1;1H" # First character clears screen, second places cursor at top-left
	print "HISTORY"
	print "-------"
	for i in range(1, int(readline.get_current_history_length())):
		print "{}. {}".format(i, readline.get_history_item(i))
	print ""
开发者ID:ElBaha,项目名称:Bahash,代码行数:7,代码来源:bahash_builtins.py

示例14: history

    def history(self):
        """ returns all the executed commands """
        if not HAVE_READLINE:
            return

        for i in range(0, readline.get_current_history_length()):
            yield readline.get_history_item(i)
开发者ID:svoutil,项目名称:zk_shell,代码行数:7,代码来源:xcmd.py

示例15: last_command

    def last_command(self):
        """ returns the last executed command """
        if not HAVE_READLINE:
            return ""

        cur_size = readline.get_current_history_length()
        return readline.get_history_item(cur_size - 1)
开发者ID:svoutil,项目名称:zk_shell,代码行数:7,代码来源:xcmd.py


注:本文中的readline.get_history_item函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。