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. python_way day14 HTML

    python_way day 14 HTML 一,标签 二.特殊字符 三,css <!DOCTYPE html> <html lang="en"> < ...

  2. XAF应用开发教程(一) 创建项目

    XAF是DevExpress公司的快速开发框架,全称eXpress Application Framework,是企业信息系统的开发利器,快速开发效果显著,在.net框架中,笔者至今没有找到一款可以与 ...

  3. DOM解析XML练习

    首先以XML文件存储数据,格式如下(作为数据库) exam.xml <?xml version="1.0" encoding="UTF-8" standa ...

  4. Android Studio常见问题 -- AndroidManifest.xml 覆盖问题

    问题如下 D:\source-code\AndroidStudio\MyApplication\app\src\main\AndroidManifest.xmlError:(14, 9) Attrib ...

  5. Class create, device create, device create file (转)

    来自:http://www.hovercool.com/en/Class_create,_device_create,_device_create_file 开始写Linux设备驱动程序的时候,很多时 ...

  6. mysql 选择性高

    选择性高是指能够过滤掉更多不需要的记录.举例来说,在一个公司里,使用性别只能过滤掉一半的人,而使用姓名一般可以过滤掉99%以上的人,因为会有重名情况,而使用员工号,选出一个,其他的全部过滤掉.也就是说 ...

  7. JavaSE复习_3 继承

    △先默认初始化,在显示初始化,在构造函数初始化 △继承的弊端:代码的耦合性增加了. △子类不能继承父类的构造方法. △子类会拥有父类的私有成员变量,但是必须通过get,set方法访问. △super不 ...

  8. hibernate的注解属性mappedBy详解

    mappedBy: 1>只有OneToOne,OneToMany,ManyToMany上才有mappedBy属性,ManyToOne不存在该属性: 2>mappedBy标签一定是定义在被拥 ...

  9. Nginx安装(zhuan)

    http://www.nginx.cn/install ************************ nginx可以使用各平台的默认包来安装,本文是介绍使用源码编译安装,包括具体的编译参数信息. ...

  10. Global Alignment(全局比对)--从算法(Needleman-Wunsch)到python实现

    很早就知道有全局比对和局部比对这两种比对方法,都是用到的动态规划的思想,知道一些罚分矩阵的概念,但一直都没有机会搞透彻,一些算法的细节也不太清楚,也没有亲手编程实现. 现在由于项目需求,需要手动写一个 ...