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

创建Ipython magic命令,用于将最后一个控制台输入保存到文件,python,logging,input,ipython,ipython-magic,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()

现在我找到了解决办法。我想在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;并将其附加到今天的日志文件中。

使用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魔法历史记录工作。在历史记录中保存旧输入,您只需选择最后一个输入并将其附加到一个日期为今天的文件中,这样您就可以将一天中的所有输入保存在一个日志文件中。重要的线路是

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

为什么不使用
%save
?它应该和在控制台中键入s一样简单和耗时,否则我也可以记录所有内容并进行排序。找到了历史魔法问题的解决方案