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自动补全的更多相关文章

  1. Linux python <tab>自动补全

    为Python添加交互模式下TAB自动补全以及命令历史功能. 1.获取python目录 [root@localhost ~]# python Python 2.6.6 (r266:84292, Jul ...

  2. Python建立Tab自动补全的脚本

    Python建立Tab自动补全的脚本 #!/usr/bin/python #python steup file import sys import readline import rlcomplete ...

  3. Python-2.7 配置tab自动补全功能

    作者博文地址:http://www.cnblogs.com/spiritman/ 之前一直使用shell编程,习惯了shell的 tab 自动补全功能,而Python的命令行却不支持 tab 自动补全 ...

  4. Python-2.7 配置 tab 自动补全功能

    作者博文地址:http://www.cnblogs.com/liu-shuai/ 之前一直使用shell编程,习惯了shell的 tab 自动补全功能,而Python的命令行却不支持 tab 自动补全 ...

  5. 如何为 .NET Core CLI 启用 TAB 自动补全功能

    如何为 .NET Core CLI 启用 TAB 自动补全功能 Intro 在 Linux 下经常可以发现有些目录/文件名,以及有些工具可以命令输入几个字母之后按 TAB 自动补全,最近发现其实 do ...

  6. Mysql命令行tab自动补全方法

    在mysql命令行有时为了方便想要按tbl键自动补全命令,以便节约时间. 具体方法如下: 第一步:修改my.cnf vi mysql/etc/my.cnf 将下图红框的代码注释,修改成如下代码: #d ...

  7. sudo和man的tab自动补全

    要加入sudo和man的tab自动补全功能,只需在~/.bashrc中加入: #Enabling tab-completioncomplete -cf sudocomplete -cf man

  8. Windows 下python的tab自动补全

    方法一:安装一个ipython就OK啦,而且关键字还能高亮显示呢 一.打开cmd,输入pip3 install ipython联网安装 二.安装成功后,cmd里运行ipython,成功啦. 方法二:写 ...

  9. Mac Tab自动补全键

    最近入手一个Mac(Mac 2019版本),在使用终端时,发现不能使用Tab键自动补全代码,网络搜寻下,发现这里有个方法,记录下,免得自己忘记: 1 / 首先找到这个图标 2 / 输入命令 nano ...

随机推荐

  1. 测试框架Mockito使用笔记

    Mockito,测试框架,语法简单,功能强大! 静态.私有.构造等方法测试需要配合PowerMock,PowerMock有Mockito和EasyMock两个版本,语法相同,本文只介绍Mockito. ...

  2. python_way day16 DOM

    Python_way day16 1.Dom  (找到html中的标签) 一.DOM 1.查找元素 直接查找 document.getElementById 根据ID获取一个标签 --->这里是 ...

  3. Promise A 规范的一个简单的浏览器端实现

    简单的实现了一个promise 的规范,留着接下来模块使用.感觉还有很多能优化的地方,有时间看看源码,或者其他大神的代码 主要是Then 函数.回调有点绕人. !(function(win) { fu ...

  4. HDU4801·二阶魔方

    题意:给定二阶魔方初始状态,问N(1 <= N <= 7)步旋转操作以内最多能使几个面相同. dfs搜索+剪枝. 魔方的每个旋转操作即对应于一个置换操作.又因为相对运动,上层左旋一次和下层 ...

  5. mysql 聚集函数需要注意的问题

    1.当没有记录的时候,使用聚集函数,会导致出现一条记录,记录的取值都是NULL,如下:mysql> select name from student where name='David';Emp ...

  6. 在Windows上安装MySQL5.7

    1. 下载安装包,这里选择压缩版mysql-5.7.16-winx64.zip: http://dev.mysql.com/downloads/mysql/ 2. 解压到安装目录,注意最好不要含有中文 ...

  7. C++——类继承

    类库:类库由类声明和实现构成.类组合了数据表示和类方法,因此提供了比函数库更加完整的程序包. 类继承:从已有的类派生出新的类,派生类继承了原有类(称为基类)的特征,包括方法. 通过类继承可以完成的工作 ...

  8. Java troubleshooting guide

    http://www.oracle.com/technetwork/java/javase/toc-135973.html --不同的 OutOfMemoryError/内存溢出,以及相关的解决

  9. WEB网页插件 如何实现 选择上传图片路径 【高级问题】

    发表于 2010-10-22 12:11 | |只看楼主       按键精灵程序里面的WEB网页插件 如何实现 选择上传图片路径 我想在上传图片的选框设置图片路径为 C:\fakepath\001. ...

  10. jquery 全选功能

    1.直接全选(复选框名字要统一) <input type="CHECKBOX" id="cbSelectAll" onclick="$('inp ...