1

今、私はそれを行う解決策を見つけました。実行可能な python コードをインタラクティブに生成するために、最後の入力を python ファイルに保存する ipython に独自のマジック コマンドを実装したい: 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;を入力します。そして、それを今日のログファイルに追加します。

4

2 に答える 2

1

%save で追加引数 -a を使用します。

これが保存したい行である場合:

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 history を使用して動作します。履歴には古い入力が保存されます。最後の入力を選択して、今日の日付でファイルに追加するだけで、ある日のすべての入力を 1 つのログ ファイルに保存できます。重要な行は

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 に答える