SVN: r25544 - trunk/quixote

Neil Schemenauer <nascheme-fVcApmY9cLvQ3/1i3zOLAti2O/[email protected]> Fri, 5 Nov 2004 18:19:34 -0500
Newsgroups gmane.comp.web.quixote.cvs
Message-ID <[email protected]>
Author: nascheme
Date: 2004-11-05 18:19:23 -0500 (Fri, 05 Nov 2004)
New Revision: 25544

Modified:
   trunk/quixote/ptl_import.py
Log:
When loading a .ptl file, check for the existence of a .pyc file and use
it if possible.  For some reason I thought ihooks would do this itself.


Modified: trunk/quixote/ptl_import.py
===================================================================
--- trunk/quixote/ptl_import.py	2004-11-05 22:12:03 UTC (rev 25543)
+++ trunk/quixote/ptl_import.py	2004-11-05 23:19:23 UTC (rev 25544)
@@ -16,6 +16,8 @@
 import sys
 import os.path
 import imp, ihooks, new
+import struct
+import marshal
 import __builtin__
 
 from ptl_compile import compile_template, PTL_EXT
@@ -33,6 +35,26 @@
     exec code in mod.__dict__
     return mod
 
+def _timestamp(filename):
+    try:
+        s = os.stat(filename)
+    except OSError:
+        return None
+    return s.st_mtime
+
+def _load_pyc(name, filename, pyc_filename):
+    try:
+        fp = open(pyc_filename, "rb")
+    except IOError:
+        return None
+    if fp.read(4) == imp.get_magic():
+        mtime = struct.unpack('<I', fp.read(4))[0]
+        ptl_mtime = _timestamp(filename)
+        if ptl_mtime is not None and mtime >= ptl_mtime:
+            code = marshal.load(fp)
+            return _exec_module_code(code, name, filename)
+    return None
+
 def _load_ptl(name, filename, file=None):
     if not file:
         try:
@@ -40,9 +62,12 @@
         except IOError:
             return None
     path, ext = os.path.splitext(filename)
-    compiled_filename = path + ".pyc"
+    pyc_filename = path + ".pyc"
+    module = _load_pyc(name, filename, pyc_filename)
+    if module is not None:
+        return module
     try:
-        output = open(compiled_filename, "wb")
+        output = open(pyc_filename, "wb")
     except IOError:
         output = None
     try:
@@ -50,7 +75,7 @@
     except:
         if output:
             output.close()
-            os.unlink(compiled_filename)
+            os.unlink(pyc_filename)
         raise
     else:
         if output: