โมดูล readline ให้ Interface ไปยัง GNU Readline Library สำหรับ Line Editing, History, Completion ใน Interactive Mode (UNIX Only)
import readline
History Management
| Function | คำอธิบาย |
|---|---|
read_history_file([filename]) | โหลด History (Default: ~/.history) |
write_history_file([filename]) | บันทึก History |
get_history_length() | Max History Lines |
set_history_length(n) | ตั้งค่า Max History Lines |
get_current_history_length() | Current History Lines |
get_history_item(index) | ดู Item ที่ Index (1-based) |
add_history(line) | เพิ่ม Line เข้า History |
remove_history_item(pos) | ลบ Item ที่ Position |
replace_history_item(pos, line) | แทนที่ Item |
clear_history() | ล้าง History |
Line Buffer & Completion
| Function | คำอธิบาย |
|---|---|
get_line_buffer() | Current Line Buffer Content |
insert_text(text) | Insert Text ที่ Cursor |
redisplay() | Refresh Display |
get_begidx() / get_endidx() | Completion Scope Indices |
parse_and_bind(string) | Parse Readline Init Command |
read_init_file([filename]) | Load Readline Init File |
ตัวอย่าง: Persistent History สำหรับ Interactive Session
import readline as rl
import os
import atexit
hist_file = os.path.join(os.path.expanduser("~"), ".my_python_hist")
try:
rl.read_history_file(hist_file)
rl.set_history_length(1000)
except FileNotFoundError:
pass
# บันทึกตอนออก
atexit.register(rl.write_history_file, hist_file)
print("History loaded. Type commands, they'll be saved on exit.")
การทดสอบ
$ python3
>>> exec(open("readline_hist.py").read())
History loaded...
>>> print("hello")
hello
>>> 2 ** 10
1024
>>> exit()
$ cat ~/.my_python_hist
print("hello")
2 ** 10
exit()
Tab Completion Setup
import readline
import rlcompleter
# Enable Tab Completion
readline.parse_and_bind("tab: complete")
# หรือ Custom Completer
readline.set_completer(rlcompleter.Completer().complete)
Key Bindings (ผ่าน parse_and_bind)
readline.parse_and_bind('"\\C-p": previous-history') # Ctrl+P
readline.parse_and_bind('"\\C-n": next-history') # Ctrl+N
readline.parse_and_bind('"\\C-r": reverse-search-history') # Ctrl+R
readline.parse_and_bind('"\\e[1;5C": forward-word') # Ctrl+Right
readline.parse_and_bind('"\\e[1;5D": backward-word') # Ctrl+Left
Best Practices
- ใช้
atexitบันทึก History อัตโนมัติ - ตั้ง
set_history_lengthป้องกันไฟล์โตมาก - Error Handling:
try/except FileNotFoundError - Windows: ใช้
pyreadline3หรือprompt_toolkit
Modern Alternative: prompt_toolkit
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
session = prompt('> ', history=FileHistory('.my_history'),
auto_suggest=AutoSuggestFromHistory())