2014-01-14 40 views
1

現在注意我找到了一個解決方案。我想實現我的IPython自己的魔法命令,最後輸入保存到Python文件,以交互方式產生可執行Python代碼: 我想過將其保存爲自己的magicfile.py在IPython的啓動目錄:創建Ipython魔術命令,用於將最後一個控制檯輸入保存到文件

#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中輸入命令,然後s;並將其附加到今天的日誌文件中。

+1

爲什麼不使用'%save '? – Matt

+0

與在控制檯中輸入s一樣,它應該既簡單又耗時,否則我也可以記錄一切並整理出來。 – beneminzl

+0

找到了歷史魔法問題的解決方案 – beneminzl

回答

0

它通過使用IPython的神奇歷史。在歷史中,舊的輸入被保存,您只需選擇最後一個輸入並將其附加到當前日期的文件中,以便您可以將一天中的所有輸入保存在一個日誌文件中。重要的行是

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

使用append參數-a和%save。

如果這是您要保存行:

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 %save documentation

相關問題