Mac OS X에서 기본 파이썬 인터프리터로 작업하고 있으며 이전 명령을 Cmd+ K(지 웁니다). 화살표 키를 사용하여 하나씩 살펴볼 수 있습니다. 그러나 bash 쉘에 --history 옵션과 같은 옵션이 있는데, 지금까지 입력 한 모든 명령이 표시됩니까?
history
쉘 내장입니다.
Mac OS X에서 기본 파이썬 인터프리터로 작업하고 있으며 이전 명령을 Cmd+ K(지 웁니다). 화살표 키를 사용하여 하나씩 살펴볼 수 있습니다. 그러나 bash 쉘에 --history 옵션과 같은 옵션이 있는데, 지금까지 입력 한 모든 명령이 표시됩니까?
history
쉘 내장입니다.
답변:
사용하여 readline.get_current_history_length()
길이를 얻기 위해, 그리고 readline.get_history_item()
각을 볼 수 있습니다.
전체 기록을 인쇄하기위한 코드 :
원 라이너 (빠른 복사 및 붙여 넣기) :
import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))
(또는 더 긴 버전 ...)
import readline
for i in range(readline.get_current_history_length()):
print (readline.get_history_item(i + 1))
원 라이너 (빠른 복사 및 붙여 넣기) :
import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])
(또는 더 긴 버전 ...)
import readline
for i in range(readline.get_current_history_length()):
print readline.get_history_item(i + 1)
참고 : get_history_item()
1에서 n까지 색인됩니다.
import readline; print '\n'.join([str(readline.get_history_item(i)) for i in range(readline.get_current_history_length())])
history()
파이썬 인터프리터 시작 스크립트 (env. var가 가리키는 스크립트)에서 위 의 기능을 추가했습니다 $PYTHONSTARTUP
. 이제부터는 history()
모든 통역 세션을 간단히 입력 할 수 있습니다. ;-)
파이썬 3 인터프리터로 역사는
~/.python_history
cat ~/.python_history
quit()
현재 세션 이력이 포함 되려면 통역사에게 필요합니다 .~/.python_history
기록을 파일에 쓰려면 다음을 수행하십시오.
import readline
readline.write_history_file('python_history.txt')
도움말 기능은 다음을 제공합니다.
Help on built-in function write_history_file in module readline:
write_history_file(...)
write_history_file([filename]) -> None
Save a readline history file.
The default filename is ~/.history.
위의 python 2.x에서만 작동하므로 python 3.x (특히 3.5)는 비슷하지만 약간 수정되었습니다.
import readline
for i in range(readline.get_current_history_length()):
print (readline.get_history_item(i + 1))
여분의 () 참고
(쉘 스크립트를 사용하여 .python_history를 구문 분석하거나 파이썬을 사용하여 위의 코드를 수정하는 것은 개인적인 취향과 상황의 문제입니다)
C:\>python -m pip install readline
=> Collecting readline
\ n Downloading https://files.pythonhosted.org/packages/f4/01/2cf081af8d880b44939a5f1b446551a7f8d59eae414277fd0c303757ff1b/readline-6.2.4.1.tar.gz (2.3MB)
\ n |████████████████████████████████| 2.3MB 1.7MB/s
\ n ERROR: Complete output from command python setup.py egg_info:
\ n ERROR: error: this module is not meant to work on Windows
\ n ----------------------------------------
\ n`오류 : C : \ Users \ dblack \ AppData \ Local \ Temp \ pip-install-s6m4zkdw의 오류 코드 1과 함께 "python setup.py egg_info"명령이 실패했습니다. \ readline`
pip install readline
만, readline
윈도우에 기본적으로 설치됩니다.
유닉스 / bash 버전과 비슷한 히스토리를 얻는 간단한 함수.
그것이 새로운 사람들을 돕기를 바랍니다.
def ipyhistory(lastn=None):
"""
param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
Also takes -ve sequence for first n history records.
"""
import readline
assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
hlen = readline.get_current_history_length()
is_neg = lastn is not None and lastn < 0
if not is_neg:
flen = len(str(hlen)) if not lastn else len(str(lastn))
for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
else:
flen = len(str(-hlen))
for r in range(1, -lastn + 1):
print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))
스 니펫 : Python3으로 테스트했습니다. python2에 결함이 있는지 알려주십시오. 샘플:
전체 역사 :
ipyhistory()
지난 10 년의 역사 :
ipyhistory(10)
처음 10 년 역사 :
ipyhistory(-10)
그것이 친구들에게 도움이되기를 바랍니다.
cut -c 8
그것들을 꺼낸다.)
@ Jason-V, 정말 감사합니다. 그런 다음 이 예제를 발견 하고 스 니펫을 소유하도록 구성했습니다.
#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
readline.read_history_file(python_history)
readline.parse_and_bind("tab: complete")
readline.set_history_length(5000)
atexit.register(readline.write_history_file, python_history)
except IOError:
pass
del os, python_history, readline, atexit
이렇게하면 명령이 별도의 줄로 인쇄됩니다.
import readline
map(lambda p:print(readline.get_history_item(p)),
map(lambda p:p, range(readline.get_current_history_length()))
)
줄 번호를 인쇄하지는 않지만 인쇄 할 줄 수를 지정할 수 있는 Doogle 의 답변을 다시 해시 하십시오.
def history(lastn=None):
"""
param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
Also takes -ve sequence for first n history records.
"""
import readline
assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
hlen = readline.get_current_history_length()
is_neg = lastn is not None and lastn < 0
if not is_neg:
for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
print(readline.get_history_item(r))
else:
for r in range(1, -lastn + 1):
print(readline.get_history_item(r))
history
쉘 명령은 다른 같은 프로그램입니다.bash
명령 에서 "옵션"이 아닙니다 .