[Python-Dev] save()/load()

Skip Montanaro skip at pobox.com
Mon Dec 1 17:10:15 EST 2003


    >> My readline history is stored in ~/.pyhist.  I can't use
    >> readline.get_history_length() to mark the start of a session for
    >> reasons which are not obvious to me.

    Phillip> get_history_length() is the length you've set for truncation,
    Phillip> not the actual length.  You want get_current_history_length(),
    Phillip> IIRC.

Yes, thanks.  I decided to dispense with accessing the "start" of the
session and force the user to simply mark() where a session is to start.
That's one extra function to remember, but seems a lot more flexible.

Appended is my current incarnation.  Still doesn't load() right, though
save() seems to work.  Usage is:

    mark()
    ... bunch of commands at the interpreter prompt ...
    save()

Any clues about what I'm doing wrong in load()?  I want to stuff the
evaluated objects into the globals() of the caller (that is, the globals for
the interactive session in most situations).

Skip

import readline
import os
import sys

# needs to match the filename the user uses!
_histfile = os.path.expanduser("~/.pyhist")

# where we save sessions
_session_file = os.path.expanduser("~/.pysession")

# mark with something valid at the interpreter but unlikely to be executed
# by the user
_marker = '((1.0+999.0j, "mark", 999.0-1.0j))'

def save():
    end = readline.get_current_history_length() - 1
    session = []
    item = readline.get_history_item(end)
    while item != _marker:
        session.insert(0, item+"\n")
        end -= 1
        item = readline.get_history_item(end)
        
    file(_session_file, 'w').writelines(session)
    print >> sys.stderr, "saved session to", _session_file

def load():
    execfile(_session_file, sys._getframe(-1).f_globals)
    print >> sys.stderr, "loaded session from", _session_file

def mark():
    readline.add_history(_marker)

import __builtin__
__builtin__.save = save
__builtin__.load = load
__builtin__.mark = mark



More information about the Python-Dev mailing list