1

Remark now I found a solution of doing it. I want to implement my own magic command in ipython which saves the last input to a python file in order to produce executable python code interactively: I thought about saving it as own magicfile.py in the ipython startup directory:

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

So right now i type in a command in ipython, then s; and it appends it to the logfile of today.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
beneminzl
  • 149
  • 2
  • 11

2 Answers2

1

Use the append argument, -a, with %save.

If this is the line you wish to save:

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

Then save it like this:

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

See the Ipython %save documentation

safay
  • 547
  • 5
  • 14
0

It works by using the IPython Magic history. In the history the old inputs are saved and you just pick the last one and append it to a file with the date of today, so that you can save all inputs from one day in one log-file. The important lines are

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')
beneminzl
  • 149
  • 2
  • 11