대화식 파이썬에서 전체 명령 내역을 어떻게 볼 수 있습니까?


149

Mac OS X에서 기본 파이썬 인터프리터로 작업하고 있으며 이전 명령을 Cmd+ K(지 웁니다). 화살표 키를 사용하여 하나씩 살펴볼 수 있습니다. 그러나 bash 쉘에 --history 옵션과 같은 옵션이 있는데, 지금까지 입력 한 모든 명령이 표시됩니까?


history쉘 명령은 다른 같은 프로그램입니다. bash명령 에서 "옵션"이 아닙니다 .
Niloct

6
정확하게 말하면 : history쉘 내장입니다.
blinry

3
들어 iPython 대답이다 %history. 그리고 -g옵션은 이전 세션을 가져 옵니다 .
Bob Stein

% history -g + % edit이 가장 효과적입니다
Dyno Fu

답변:



250

전체 기록을 인쇄하기위한 코드 :

파이썬 3

원 라이너 (빠른 복사 및 붙여 넣기) :

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

파이썬 2

원 라이너 (빠른 복사 및 붙여 넣기) :

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까지 색인됩니다.


31
한 라이너 :import readline; print '\n'.join([str(readline.get_history_item(i)) for i in range(readline.get_current_history_length())])
Matt

24
이 답변 (및 비 예제)은 사람들에게 예가 얼마나 중요한지를 보여줍니다. 감사.
Tim S.

8
멋있는! history()파이썬 인터프리터 시작 스크립트 (env. var가 가리키는 스크립트)에서 위 의 기능을 추가했습니다 $PYTHONSTARTUP. 이제부터는 history()모든 통역 세션을 간단히 입력 할 수 있습니다. ;-)
sxc731

2
내가 잊을 때마다, 어떻게되는지, 답을 위해 여기 왔습니다, 데니스에게 감사합니다.
Felipe Valdes

3
나는 이것을 아는 사람에게 별표를 썼다. 👍🏽
berto

45

파이썬 3 인터프리터로 역사는
~/.python_history


나는이 디렉토리가없고 파이썬 3.5.2를 사용한다

이것은 유닉스 계열 OS를위한 것입니다. 다음과 같이 macOS에서 내 기록을 검색 할 수있었습니다.cat ~/.python_history
Ryan H.

1
이 답변에 감사드립니다. 나중에이 문서에서 다루는 것을 발견했습니다. docs.python.org/3/library/site.html#readline-configuration
Jason V.

4
불행히도, 가상 환경을 사용할 때 기록이 업데이트되지 않는 것 같습니다 :-/
ChrisFreeman

4
quit()현재 세션 이력이 포함 되려면 통역사에게 필요합니다 .~/.python_history
plexoos

9

기록을 파일에 쓰려면 다음을 수행하십시오.

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.

이것은 루비의 역사와 같은 파이썬 세션에서 지속됩니까?
lacostenycoder

이 답변은 readline 함수 이전에 작성되었지만 readline.write_history_file을 사용하지 않는 이유는 무엇입니까? @lacostenycoder readline을 사용하여 지속되는 기록 파일을 읽고 쓸 수 있습니다.
Joe Holloway

@JoeHolloway 쿨 감사합니다! 나는 대답을 바꿨다!
Martin Thoma

4

위의 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를 구문 분석하거나 파이썬을 사용하여 위의 코드를 수정하는 것은 개인적인 취향과 상황의 문제입니다)


3
Win10 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`
bballdave025

1
@ bballdave025 예, 당신은 할 수 없습니다 pip install readline만, readline윈도우에 기본적으로 설치됩니다.
Josiah Yoder

글쎄, 그것은 일을 더 쉽게 만듭니다. 감사합니다 @JosiahYoder
bballdave025

@ bballdave025 나는 창에 기본적으로 설치되어 있지 않다는 것을 알았지 만 링크를 따라 가면 지침에 세부 정보가 표시됩니다-pyreadline 설치 등.
Josiah Yoder

4

IPython에서는 %history -g전체 명령 기록을 제공해야합니다. 기본 구성은 또한 기록을 사용자 디렉토리의 .python_history 파일에 저장합니다.


3

유닉스 / 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)

그것이 친구들에게 도움이되기를 바랍니다.


안녕, 고마워 코드 스 니펫을 xx.py 파일로 만들었습니다. 그런 다음 파이썬을 연 후 xx를 가져 왔습니다. ipyhistory ()를 시도했지만 ">>> ipyhistory Traceback (가장 최근 호출) : <module> NameError : name 'ipyhistory'is not defined"의 파일 "<stdin>", 1 행. 뭐가 문제 야?
Chan Kim

나는 줄 번호를 인쇄하지 않도록 수정했습니다. 줄 번호는 보통 나에게 방해가되기 때문에 줄 제한 기능이 마음에 들었습니다. (유닉스에서도 나는 보통 cut -c 8그것들을 꺼낸다.)
Josiah Yoder

1

@ 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 

1

이렇게하면 명령이 별도의 줄로 인쇄됩니다.

import readline
map(lambda p:print(readline.get_history_item(p)),
    map(lambda p:p, range(readline.get_current_history_length()))
)

코드 형식을보다 구체적으로 지정할 수 있습니까? 괄호가 일치하지 않는다고 말하는가?
Idea4life 2018 년

간단한 들여 쓰기로 서식을 수정했습니다. @AleksAndreev 당신은 downvote를 제거 할 수 있습니다.
ChrisFreeman

0

줄 번호를 인쇄하지는 않지만 인쇄 할 줄 수를 지정할 수 있는 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))
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.