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()
$

更新於:2019年7月30日

671 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告