python——使用readline库实现tab自动补全

python

Input History

readline tracks the input history automatically. There are two different sets of functions for working with the history. The history for the current session can be accessed with get_current_history_length()and get_history_item(). That same history can be saved to a file to be reloaded later using write_history_file() and read_history_file(). By default the entire history is saved but the maximum length of the file can be set with set_history_length(). A length of -1 means no limit.

import readline

import logging

import os

LOG_FILENAME = '/tmp/completer.log'

HISTORY_FILENAME = '/tmp/completer.hist'

logging.basicConfig(filename=LOG_FILENAME,

level=logging.DEBUG,

)

def get_history_items():

return [ readline.get_history_item(i)

for i in xrange(1, readline.get_current_history_length() + 1)

]

class HistoryCompleter(object):

def __init__(self):

self.matches = []

return

def complete(self, text, state):

response = None

if state == 0:

history_values = get_history_items()

logging.debug('history: %s', history_values)

if text:

self.matches = sorted(h

for h in history_values

if h and h.startswith(text))

else:

self.matches = []

logging.debug('matches: %s', self.matches)

try:

response = self.matches[state]

except IndexError:

response = None

logging.debug('complete(%s, %s) => %s',

repr(text), state, repr(response))

return response

def input_loop():

if os.path.exists(HISTORY_FILENAME):

readline.read_history_file(HISTORY_FILENAME)

print 'Max history file length:', readline.get_history_length()

print 'Startup history:', get_history_items()

try:

while True:

line = raw_input('Prompt ("stop" to quit): ')

if line == 'stop':

break

if line:

print 'Adding "%s" to the history' % line

finally:

print 'Final history:', get_history_items()

readline.write_history_file(HISTORY_FILENAME)

# Register our completer function

readline.set_completer(HistoryCompleter().complete)

# Use the tab key for completion

readline.parse_and_bind('tab: complete')

# Prompt the user for text

input_loop()

The HistoryCompleter remembers everything you type and uses those values when completing subsequent inputs.

$ python readline_history.py

Max history file length: -1

Startup history: []

Prompt ("stop" to quit): foo

Adding "foo" to the history

Prompt ("stop" to quit): bar

Adding "bar" to the history

Prompt ("stop" to quit): blah

Adding "blah" to the history

Prompt ("stop" to quit): b

bar blah

Prompt ("stop" to quit): b

Prompt ("stop" to quit): stop

Final history: ['foo', 'bar', 'blah', 'stop']

The log shows this output when the “b” is followed by two TABs.

DEBUG:root:history: ['foo', 'bar', 'blah']

DEBUG:root:matches: ['bar', 'blah']

DEBUG:root:complete('b', 0) => 'bar'

DEBUG:root:complete('b', 1) => 'blah'

DEBUG:root:complete('b', 2) => None

DEBUG:root:history: ['foo', 'bar', 'blah']

DEBUG:root:matches: ['bar', 'blah']

DEBUG:root:complete('b', 0) => 'bar'

DEBUG:root:complete('b', 1) => 'blah'

DEBUG:root:complete('b', 2) => None

When the script is run the second time, all of the history is read from the file.

$ python readline_history.py

Max history file length: -1

Startup history: ['foo', 'bar', 'blah', 'stop']

Prompt ("stop" to quit):

There are functions for removing individual history items and clearing the entire history, as well.

最后效果是你输入的历史的foo被记录了下来,下次打开的时候输入fo然后tab就可以自动提示foo来补全了!

以上是 python——使用readline库实现tab自动补全 的全部内容, 来源链接: utcz.com/z/386537.html

回到顶部