readline 모듈이란?
readline 모듈은 UNIX 계열 시스템에서만 사용할 수 있는 파이썬 전용 모듈입니다. 이 모듈은 파이썬 인터프리터에서 히스토리(history) 파일을 더욱 쉽게 읽고 쓸 수 있도록 다양한 함수를 제공합니다. readline 모듈은 직접 임포트하여 사용할 수도 있고, rlcompleter 모듈과 함께 사용할 수도 있습니다.
또한 이 모듈의 설정은 내장 함수인 input()의 프롬프트 동작과 대화형(interactive) 프롬프트에도 영향을 미칩니다.
macOS 환경에서의 주의사항
맥(MAC OS X) 기반 시스템에서는 readline 모듈이 libedit 라이브러리를 기반으로 구현됩니다. libedit의 설정 방식은 GNU readline과 다르므로, 플랫폼 간 호환성을 고려할 때 이 점을 유의해야 합니다.
모듈 임포트 방법
readline 모듈을 사용하려면 파이썬 코드에서 먼저 모듈을 임포트해야 합니다.
import readline
GNU readline의 주요 함수
| 번호 | 함수 및 설명 |
|---|---|
| 1 | readline.parse_and_bind(string) readline 초기화 파일에서 한 줄을 가져와 파싱한 후 실행합니다. |
| 2 | readline.get_line_buffer() 현재 라인 버퍼(line buffer)의 내용을 반환합니다. |
| 3 | readline.insert_text(string) 명령줄(command line)에 텍스트를 삽입합니다. |
| 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) 인덱스(index)를 사용하여 특정 히스토리 항목을 가져옵니다. |
| 12 | readline.remove_history_item(pos) 위치(position)를 기준으로 해당 히스토리 항목을 삭제합니다. |
| 13 | readline.replace_history_item(pos, line) 위치(position)를 기준으로 해당 히스토리 항목을 새 라인으로 교체합니다. |
| 14 | readline.redisplay() 현재 라인 버퍼의 내용을 화면에 다시 표시합니다. |
| 15 | readline.get_begidx() 탭(tab) 자동완성 범위의 시작 인덱스를 반환합니다. |
| 16 | readline.get_endidx() 탭(tab) 자동완성 범위의 끝 인덱스를 반환합니다. |
| 17 | readline.add_history(line) 히스토리 버퍼의 마지막에 한 줄을 추가합니다. |
실전 예제: 히스토리 파일 저장하기
아래 코드는 홈 디렉터리에 히스토리 파일을 읽고 저장하는 예제입니다. 이 코드는 대화형(interactive) 모드에서 컴파일 후 실행할 때 동작하며, 파이썬 셸을 종료하는 시점에 히스토리 파일이 저장됩니다.
예제 코드
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()
$
실행 결과를 보면, atexit.register()를 통해 셸 종료 시점에 히스토리가 자동으로 파일에 기록되는 것을 확인할 수 있습니다. 이처럼 readline 모듈을 활용하면 세션 간 명령어 히스토리를 편리하게 관리할 수 있습니다.