Python GNU readline 接口
readline 是一个 UNIX 特定的模块。它定义了许多函数,以便更轻松地从 Python 解释器中读取和写入历史文件。我们可以直接使用此模块,也可以使用 rlcompleter 模块。此模块的设置可能会影响内置的 input() 方法提示以及交互式提示。
对于基于 MAC 的系统(在 MAC OS X 上),此 readline 模块可以使用 libedit 库实现。libedit 的配置与 GNU readline 不同。
要使用此模块,需要在 Python 代码中导入 readline 模块。
import readline
GNU readline 的一些方法如下:
| 序号 | 函数及描述 |
|---|---|
| 1 | readline.parse_and_bind(string) 从 readline 初始化文件读取单行并解析后执行。 |
| 2 | readline.get_line_buffer() 获取行缓冲区的当前内容。 |
| 3 | readline.insert_text(string) 将文本插入到命令行。 |
| 4 | readline.read_init_file([filename]) 解析 readline 初始化文件。默认值为上次提供的值。 |
| 5 | readline.read_history_file([filename]) 从给定文件读取历史记录。默认文件名是 ~/.history |
| 6 | readline.write_history_file([filename]) 将历史记录保存到给定文件。默认文件是 ~/.history |
| 7 | readline.clear_history() 清除当前历史记录。 |
| 8 | readline.get_history_length() 获取历史文件的最大长度。 |
| 9 | readline.set_history_length(length) 设置历史文件长度(行数)。 |
| 10 | readline.get_current_history_length() 获取历史文件中总行数。 |
| 11 | readline.get_history_item(index) 使用索引获取历史项目。 |
| 12 | readline.remove_history_item(pos) 按位置删除历史记录。 |
| 13 | readline.replace_history_item(pos, line) 按位置替换历史记录。 |
| 14 | readline.redisplay() 显示行缓冲区的当前内容。 |
| 15 | readline.get_begidx() 获取制表符补全范围的起始索引。 |
| 16 | readline.get_endidx() 获取制表符补全范围的结束索引。 |
| 17 | readline.add_history(line) 在历史缓冲区的末尾追加一行。 |
此代码用于读取历史文件并将其存储在主目录中。在交互模式下编译和运行时,此代码将起作用。退出 Python shell 后,它将存储历史文件。
示例代码
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
在交互式 shell 中运行:
$ 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()
$
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP