2014-01-14 4 views
1

설명 이제 해답을 발견했습니다. 을 내가 ipython 시작 디렉토리에 자신의 magicfile.py로 저장에 대한 생각 :마지막 콘솔 입력을 파일에 저장하기 위해 Ipython magic 명령을 작성하십시오.

#Save this file in the ipython profile startup directory which can be found via: 
#import IPython 
#IPython.utils.path.locate_profile() 
from IPython.core.magic import (Magics, magics_class, line_magic, 
           cell_magic, line_cell_magic) 

# The class MUST call this class decorator at creation time 
@magics_class 
class MyMagics(Magics): 

    @line_magic 
    def s(self, line): 
     import os 
     import datetime 
     today = datetime.date.today() 
     get_ipython().magic('%history -l 1 -t -f history.txt /') 
     with open('history.txt', 'r') as history: 
      lastinput = history.readline() 
      with open('ilog_'+str(today)+'.py', 'a') as log: 
       log.write(lastinput) 
     os.remove('history.txt') 
     print 'Successfully logged to ilog_'+str(today)+'.py!' 

# In order to actually use these magics, you must register them with a 
# running IPython. This code must be placed in a file that is loaded once 
# IPython is up and running: 
ip = get_ipython() 
# You can register the class itself without instantiating it. IPython will 
# call the default constructor on it. 
ip.register_magics(MyMagics) 
나는 대화 형으로 실행 파이썬 코드를 생성하기 위해 파이썬 파일에 마지막 입력을 저장 ipython 내 자신 마술 명령을 구현하려면

이제 ipython에서 명령을 입력 한 다음 s; 오늘의 로그 파일에 추가합니다.

+1

% save '를 사용하지 않는 이유는 무엇입니까? – Matt

+0

콘솔에 s를 입력하는 것이 쉽고 시간이 많이 걸릴 것입니다. 그렇지 않으면 모든 것을 기록하고 정렬 할 수도 있습니다. – beneminzl

+0

히스토리 마법의 문제점에 대한 해결책을 찾았습니다. – beneminzl

답변

0

를 참조하십시오. 기록에서 이전 입력 내용이 저장되고 마지막 날짜를 선택하여 오늘 날짜가있는 파일에 추가합니다. 그러면 하루의 모든 입력을 하나의 로그 파일에 저장할 수 있습니다. 중요한 라인은

get_ipython().magic('%history -l 1 -t -f history.txt /') 
with open('history.txt', 'r') as history: 
    lastinput = history.readline() 
    with open('ilog_'+str(today)+'.py', 'a') as log: 
     log.write(lastinput) 
os.remove('history.txt') 
0

% save와 함께 append 인수 -a를 사용하십시오.

이 저장하고자하는 라인 인 경우 :

In [10]: print 'airspeed velocity of an unladen swallow: ' 

다음과 같이 저장이 :

In [11]: %save -a IPy_session.py 10 
The following commands were written to file `IPy_session.py`: 
print 'airspeed velocity of an unladen swallow: ' 

그것은이 IPython 매직 기록을 사용하여 작동 Ipython %save documentation