[Python-Dev] save()/load()
Skip Montanaro
skip at pobox.com
Mon Dec 1 15:35:33 EST 2003
I lost the original thread, but my first thought was to use the readline
module's history capability to save and reload a "session". This hack
partially works for what little testing I've done (place it in
sitecustomize.py):
import readline
import os
import sys
_start_len = len(open(os.path.expanduser("~/.pyhist")).readlines())
_session_file = os.path.expanduser("~/.pysession")
def save(f=_session_file, start=_start_len):
sf = open(f, 'w')
while True:
line = readline.get_history_item(start)
start += 1
if line is None:
break
if line.startswith('save(') or line.startswith('load('):
continue
sf.write(line+"\n")
def load(f=_session_file):
execfile(f, sys._getframe(-1).f_globals)
import __builtin__
__builtin__.save = save
__builtin__.load = load
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. When I first started futzing around with it,
readline.get_history_length() returned 9934. Now, even though my ~/.pyhist
file has more than 9960 lines, get_history_length() seems to always return
-1, thus making it useless in this context.
Here's a simple session showing save() and load() within the same session:
>>> import math
>>> print math.sin(47)
0.123573122745
>>> def f():
... return math.sin(48)
...
>>> save()
>>> load()
0.123573122745
>>> f
<function f at 0x431830>
>>> f()
-0.76825466132366682
Note that f may not be a new f, however. A call to load() in a fresh
session fails to place 'f' in the session's globals. I'm not sure why. Any
ideas?
Skip
More information about the Python-Dev
mailing list