Python GNU readline接口
该readline的是UNIX特定模块。它定义了许多从python解释器以更简单的方式读取和写入历史文件的函数。我们可以直接使用此模块,也可以使用rlcompleter模块。此模块设置可能会影响内置input()方法提示以及交互式提示。
对于基于MAC的系统(在MACOSX上),可以使用libedit库来实现此readline模块。libedit配置不同于GNUreadline。
要使用此模块,我们需要在python代码中导入readline模块
import readline
GNUreadline的一些方法如下-
readline.parse_and_bind(字符串)
从readline初始化文件中提取一行,并在解析后执行它们。
readline.get_line_buffer()
获取行缓冲区的当前内容
readline.insert_text(字符串)
在命令行中插入文本
readline.read_init_file([文件名])
解析readline初始化文件。默认值为最后提供的值。
readline.read_history_file([文件名])
从给定文件中读取历史记录。默认文件名是〜/.history
readline.write_history_file([文件名])
将历史记录保存到给定文件中。默认文件是〜/.history
readline.clear_history()
清除当前历史记录
readline.get_history_length()
获取历史文件的最大长度。
readline.set_history_length(length)
设置历史文件的长度(行数)
阅读线。get_current_history_length()
获取历史文件中的总行数
readline.get_history_item(索引)
使用索引获取历史项
readline.remove_history_item(pos)
按位置删除历史记录
readline.replace_history_item(行,行)
按位置替换历史记录
readline.redisplay()
显示行缓冲区的当前内容
readline.get_begidx()
获取制表符完成范围的起始索引
readline.get_endidx()
获取制表符完成范围的结束索引
readline.add_history(行)
在历史记录缓冲区的末尾追加一行
此代码用于读取历史记录文件并将其存储在主目录中。该代码在编译并以交互方式运行时将起作用。退出pythonshell后,它将存储历史记录文件。
范例程式码
import readline as rl
import os
import atexit
my_hist_file = os.path.join(os.path.expanduser("~"), ".my_python_hist")
try:
rl.read_history_file(my_hist_file)
rl.clear_history()
except FileNotFoundError:
pass
print("Done")
atexit.register(rl.write_history_file, my_hist_file)
del os, my_hist_file在交互式外壳中运行-
$ python3
Python 3.6.5 (default, Apr 1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exec(open("./readline_task.py").read())
Done
>>> print("readline_task.py is ececuted")
readline_task.py is ececuted
>>> print("History File will be updated after exit.")
History File will be updated after exit.
>>> 2 ** 10
1024
>>> 2 ** 20
1048576
>>> 2 ** 30
1073741824
>>> import math
>>> math.factorial(6)
720
>>> exit()$ cat ~/.my_python_hist
print("readline_task.py is ececuted")
print("History File will be updated after exit.")
2 ** 10
2 ** 20
2 ** 30
import math
math.factorial(6)
exit()
$