現在注意我找到了一個解決方案。我想實現我的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;並將其附加到今天的日誌文件中。
爲什麼不使用'%save'? –
Matt
與在控制檯中輸入s一樣,它應該既簡單又耗時,否則我也可以記錄一切並整理出來。 – beneminzl
找到了歷史魔法問題的解決方案 – beneminzl