Trash: Cookbook Saving the session on exit

Brian Granger edited this page Feb 13, 2013 · 1 revision
Clone this wiki locally

Even if we can start the logger in the current session by calling the magic function %logstart, and control it with %logoff, %logon and %logstate, I like the way that R asks to save the session before exit.

Here is a simple code to transform the IPython shell logger like the R one. Just copy the code below in ~/.ipython/ (or whatever you want) and append ip.ex("import logger") to ~/.ipython/

import IPython.ipapi
import sys, os

ip = IPython.ipapi.get()
LOGNAME = ".ipython_history.log"

def startup_logger(self):
    """ Executed at the ipython startup for loading last saved session
    if os.path.exists(LOGNAME):
        p = raw_input("Load last saved session in the current directory ([y]/n)? ")
        if (p.lower() == 'y') or (p == ''):
            ip.magic('run -i -e %s' %LOGNAME)

def shutdown_logger(self):
    """ Prompts for saving the current session during shutdown

    p = raw_input("Save current session (y/[n])? ")
    if p.lower() == 'y':
        #ip.magic('logstart %s over' %LOGNAME)
        shell =
        logger = shell.logger
        head = shell.loghead_tpl % (LOGNAME, '[]')
        #head = "#saved session in the current directory"
            started = logger.logstart(logfname=LOGNAME, loghead=head, logmode='append')
            print("Couldn't save session: %s" % sys.exc_info()[1])
        input_hist = shell.input_hist

ip.set_hook('late_startup_hook', startup_logger)    
ip.set_hook('shutdown_hook', shutdown_logger)