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

2024-05-16 02:57:47 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我找到了一个解决办法。我想在ipython中实现我自己的magic命令,它将最后的输入保存到python文件中,以便交互式地生成可执行的python代码: 我想把它存为自己的magicfile.py文件在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;它将它附加到今天的日志文件中。在


Tags: 文件thepyimporttxtregistertodaywith
2条回答

它通过使用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')

使用append参数-a和%save。在

如果这是您希望保存的行:

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

然后这样保存:

^{pr2}$

参见Ipython %save documentation

相关问题 更多 >