-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathreadline_history.py
89 lines (73 loc) · 2.14 KB
/
readline_history.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""
#end_pymotw_header
try:
import gnureadline as readline
except ImportError:
import readline
import logging
import os
LOG_FILENAME = '/tmp/completer.log'
HISTORY_FILENAME = '/tmp/completer.hist'
logging.basicConfig(
format='%(message)s',
filename=LOG_FILENAME,
level=logging.DEBUG,
)
def get_history_items():
num_items = readline.get_current_history_length() + 1
return [
readline.get_history_item(i)
for i in range(1, num_items)
]
class HistoryCompleter:
def __init__(self):
self.matches = []
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 = input('Prompt ("stop" to quit): ')
if line == 'stop':
break
if line:
print('Adding {!r} to the history'.format(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()