readline UNIX 전용 모듈입니다. 파이썬 인터프리터에서 더 쉽게 히스토리 파일을 읽고 쓸 수 있도록 여러 기능을 정의합니다. 이 모듈을 직접 사용하거나 rlcompleter를 사용할 수 있습니다. 기준 치수. 이 모듈 설정은 내장된 input() 메서드 프롬프트와 대화형 프롬프트에 영향을 줄 수 있습니다.
MAC 기반 시스템(MAC OS X)의 경우 이 readline 모듈은 libedit 라이브러리를 사용하여 구현할 수 있습니다. libedit 구성은 GNU readline과 다릅니다.
이 모듈을 사용하려면 파이썬 코드에서 readline 모듈을 가져와야 합니다.
import readline
GNU readline의 몇 가지 방법은 다음과 같습니다 -
| 시니어 번호 | 기능 및 설명 |
|---|---|
| 1 | readline.parse_and_bind(문자열) readline init 파일에서 한 줄만 가져와서 파싱 후 실행합니다. |
| 2 | readline.get_line_buffer() 라인 버퍼의 현재 내용 가져오기 |
| 3 | readline.insert_text(문자열) 명령줄에 텍스트 삽입 |
| 4 | readline.read_init_file([파일 이름]) readline 초기화 파일을 구문 분석합니다. 기본값은 마지막으로 제공된 값입니다. |
| 5 | readline.read_history_file([파일 이름]) 주어진 파일에서 기록을 읽습니다. 기본 파일 이름은 ~/.history 입니다. |
| 6 | readline.write_history_file([파일 이름]) 주어진 파일에 히스토리를 저장합니다. 기본 파일은 ~/.history 입니다. |
| 7 | readline.clear_history() 현재 기록 지우기 |
| 8 | readline.get_history_length() 히스토리 파일의 최대 길이를 가져옵니다. |
| 9 | readline.set_history_length(길이) 히스토리 파일 길이 설정(라인 수) |
| 10 | 리드라인. get_current_history_length() 히스토리 파일의 총 줄 수 가져오기 |
| 11 | readline.get_history_item(색인) 인덱스를 사용하여 히스토리 항목 가져오기 |
| 12 | readline.remove_history_item(pos) 위치별 기록 제거 |
| 13 | readline.replace_history_item(위치, 줄) 위치로 기록 바꾸기 |
| 14 | readline.redisplay() 라인 버퍼의 현재 내용 표시 |
| 15 | readline.get_begidx() 탭 완성 범위의 시작 인덱스 가져오기 |
| 16 | readline.get_endidx() 탭 완성 범위의 끝 인덱스 가져오기 |
| 17 | readline.add_history(줄) 히스토리 버퍼의 끝에 한 줄 추가 |
이 코드는 히스토리 파일을 읽고 홈 디렉토리에 저장하는 데 사용됩니다. 코드는 컴파일되고 대화형 모드에서 실행될 때 작동합니다. 파이썬 셸을 종료하면 히스토리 파일이 저장됩니다.
예시 코드
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()
$