创建Ipython magic命令以将最后一个控制台输入保存到文件

时间:2014-01-14 13:24:41

标签: python logging input ipython ipython-magic

备注现在我找到了解决方案。我想在ipython中实现我自己的magic命令,它将最后一个输入保存到python文件,以便以交互方式生成可执行的python代码: 我想在ipython启动目录中将它保存为自己的magicfile.py:

#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;它将它附加到今天的日志文件中。

2 个答案:

答案 0 :(得分:1)

使用附加参数-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

答案 1 :(得分:0)

它使用IPython Magic历史记录。在历史记录中保存旧输入,您只需选择最后一个并将其附加到具有今天日期的文件,以便您可以将一天中的所有输入保存在一个日志文件中。重要的是

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