2016-09-14 4 views
2

대화 형 셸이 닫힌 후에도 지속적인 기록을 유지하도록 CMD module from Python을 구성 할 수있는 방법이 있습니까?Python cmd 모듈의 영구 이력

위로 및 아래로 키를 누르면 이전 세션에서 이전에 쉘에 입력했던 명령에 액세스하고 싶습니다.이 세션 중에 방금 입력 한 것과 마찬가지로 Python 스크립트도 실행했습니다. 그 어떤 도움 cmd를이 readline module

답변

6

readline에서 수입 set_completer를 사용하는 경우

가 자동으로 입력 모두의 역사를 유지합니다. 추가 할 필요가있는 것은 기록을로드하고 저장하기위한 후크뿐입니다.

readline.read_history_file(filename)을 사용하여 내역 파일을 읽습니다. 지금까지 기록을 유지하려면 readline.write_history_file()을 사용하여 readline에게 알려주십시오. 당신은 바운드없이 성장에서이 파일을 유지하는 readline.set_history_length()을 사용할 수 있습니다 :

import os.path 
try: 
    import readline 
except ImportError: 
    readline = None 

histfile = os.path.expanduser('~/.someconsole_history') 
histfile_size = 1000 

class SomeConsole(cmd.Cmd): 
    def preloop(self): 
     if readline and os.path.exists(histfile): 
      readline.read_history_file(histfile) 

    def postloop(self): 
     if readline: 
      readline.set_history_length(histfile_size) 
      readline.write_history_file(histfile) 

나는 점에 어디 명령 루프 시작하고 끝을 로딩 및 저장을 트리거 할 Cmd.preloop()Cmd.postloop() 후크를 사용했다.

readline을 설치하지 않은 경우 precmd() method을 추가하고 입력 한 명령을 직접 녹음하여 시뮬레이션 할 수 있습니다.

+0

답장을 보내 주셔서 감사합니다. 원하시는대로 기존 기록 목록 기능을 변경하지 않으셔도됩니다. – PJConnol

+0

@PJConnol :'readline' 라이브러리는 완료 기능을 위해서만 사용됩니다; 나는 (글로벌) history readline이 여기서 플레이를 유지할 수 있다고 생각하지 않는다. –

+0

괜찮아요. 다시 고마워요. – PJConnol