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. hdu 1086(计算几何入门题——计算线段交点个数)

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=1086 You can Solve a Geometry Problem too Time Limit: 2 ...

  2. flex中实现自动换行

    有时候由于label .button等控件中需要用到text属性显示出文本,文本太长就涉及到换行问题,解决方法如下 在actionScript 需要用“  ”实现换行,在需要换行的地方加上它就OK. ...

  3. 适应各浏览器图片裁剪无刷新上传jQuery插件(转)

    看到一篇兼容性很强的图片无刷新裁剪上传的帖子,感觉很棒.分享下!~ 废话不多说,上效果图. 一.首先建立如下的一个page <!DOCTYPE html> <html xmlns=& ...

  4. mysql Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

    错误原因:/var/lib/mysql目录中socket文件不存在.连接mysql服务器有两种方式:tcp连接,通过socket文件连接.通过socket文件,启动mysql服务,mysql服务会自动 ...

  5. python接口的调用方法

    第一个图灵机器人接口实例: #!/usr/bin/env python # -*- coding: utf_8 -*- import urllib2,urllib import json import ...

  6. Google MapReduce/GFS/BigTable三大技术的论文中译版

    今天查找分布式计算的有关资料,发现Google的三大核心技术MapReduce.GFS和BigTable的论文都已经被翻译成高质量的中文,更巧的是,这三篇中译版的原发地都是CSDN的Blog.其中最新 ...

  7. Java编程思想学习笔记_4(异常机制,容器)

    一.finally语句注意的细节: 当涉及到break和continue语句的时候,finally字句也会得到执行. public class Test7 { public static void m ...

  8. JavaSE 复习_4 接口多态和内部类

    △abstract不可以修饰成员变量 △一个类可以没有抽象方法,可以定义为抽象类,这样的目的是不能让其他类建立本类对象,交给子类完成. △abstract和static(可以被类名调用方法,但是抽象方 ...

  9. WDS的原理

    WDS的原理 WDS 即 Wireless Distribution System,是无线网络部署延展系统的简称,指用多个无线网络相互联结的方式构成一个整体的无线网络.简单地说,WDS就是利用两个(或 ...

  10. iOS开发之如何修改Mac截屏保存路径

    如何修改Mac截屏保存路径   MAC OS X系统默认的截图路径是桌面文件夹,默认的截图格式是 PNG 图片格式,如何自定义设置呢? 截图保存路径 打开终端(Terminal)并输入如下命令: de ...