1

备注现在我找到了解决方案。我想在 ipython 中实现我自己的魔法命令,它将最后一个输入保存到 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; 并将其附加到今天的日志文件中。

4

2 回答 2

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 文档

于 2014-07-16T17:36:08.550 回答
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')
于 2014-09-11T10:38:35.350 回答