Guest User

Untitled

a guest
Jan 23rd, 2011
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.06 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import types
  3. import marshal
  4. import pickle
  5.  
  6. def dumpfunction(function):
  7.     """
  8.    Returns a serialized version of the given function.
  9.    """
  10.     return marshal.dumps((
  11.             function.func_code,
  12.             function.func_defaults,
  13.             function.func_dict,
  14.             function.func_doc,
  15.             function.func_name))
  16.  
  17. def loadfunction(pickledfunction):
  18.     """
  19.    Returns a function loaded from data produced by the dumpfunction method
  20.    of this module.
  21.    """
  22.     pairing = zip(
  23.         ("func_code", "func_defaults", "func_dict", "func_doc", "func_name"),
  24.         marshal.loads(pickledfunction))
  25.  
  26.     dummyfunction = lambda: None
  27.     for attribute, value in pairing:
  28.         setattr(dummyfunction, attribute, value)
  29.  
  30.     return dummyfunction
  31.  
  32.  
  33. def dumpcontext(context, outstream=None):
  34.     """
  35.    Serializes the state of the environment passed into the function. A two
  36.    element tuple is returned containing the serialized data and a list
  37.    containing the names of the variables that could not be serialized.
  38.    """
  39.     codevat = dict()
  40.     moduledict = dict()
  41.     picklejar = dict()
  42.     unpickled = []
  43.  
  44.     for variablename, variable in context.iteritems():
  45.         if variablename.startswith("__"):
  46.             continue
  47.  
  48.         if isinstance(variable, types.ModuleType):
  49.             moduledict[variablename] = variable.__name__
  50.  
  51.         else:
  52.             if (isinstance(variable, types.FunctionType)
  53.                     and variable.__module__ == "__main__"):
  54.                 codevat[variablename] = dumpfunction(variable)
  55.             else:
  56.                 try:
  57.                     pickle.dumps(variable)
  58.                     picklejar[variablename] = variable
  59.                 except Exception:
  60.                     unpickled.append(variablename)
  61.  
  62.     container = (codevat, moduledict, pickle.dumps(picklejar))
  63.  
  64.     if outstream:
  65.         pickle.dump(container, outstream)
  66.         return unpickled
  67.  
  68.     return (pickle.dumps(container), unpickled)
  69.  
  70. def loadcontext(contextdump, target, raiseonerror=False):
  71.     """
  72.    Restores an interpreter environment using the data produced by the
  73.    complimentary function dumpcontext.
  74.    """
  75.     if hasattr(contextdump, "read"):
  76.         codevat, moduledict, picklejar = pickle.load(contextdump)
  77.     else:
  78.         codevat, moduledict, picklejar = pickle.loads(contextdump)
  79.  
  80.     module = "__%s__" % __name__
  81.     exec("import pickle as __pickle__", target)
  82.     exec("import %s as %s" % (__name__, module), target)
  83.  
  84.     for importname, modulename in moduledict.iteritems():
  85.         try:
  86.             exec("import %s as %s" % (importname, modulename), target)
  87.         except:
  88.             if raiseonerror:
  89.                 raise
  90.  
  91.     for name, dump in codevat.iteritems():
  92.         try:
  93.             exec("%s = %s.loadfunction(%r)" % (name, module, dump), target)
  94.         except:
  95.             if raiseonerror:
  96.                 raise
  97.  
  98.     exec("locals().update(__pickle__.loads(%r))" % picklejar, target)
  99.     exec("del %s, __pickle__" % module, target)
Advertisement
Add Comment
Please, Sign In to add comment