checking pyc files against source code

Jeremy Lowery jermnsar at hotmail.com
Tue May 20 04:06:47 EDT 2003


I've implemented a new loader using ihooks, overriding the load_source
method. new types have been added to get_suffixes in the hooks.
(appending new ones to imp.get_suffixes()).

I also compile the source code into pyc files to make importing the
modules in subsequent python runs faster (It is faster b/c the
compilation of the custom files takes a good chunk of CPU time).

However, now when the custom files are edited, no change is seen until
the .pyc file is deleted and then recreated by the import mechanism. I
figure some os.getmtime stuff will be needed, but I"m not sure where.
I would like it to behave like normal python files (If you change the
.py file, the .pyc file is automatically recreated. Not sure where in
the plumbing this happens). Any help?

here is the code for load_source

def load_source(self, name, filename, file):
        print 'having to load %s' % filename
        source = file.read(-1)
        file.close()
        
        cname = name[name.rfind('.')+1:]
        compiler = Compiler(source=source, moduleName=cname)
        code = str(compiler)
        module = imp.new_module(name)
        module.__file__ = filename
        exec code in module.__dict__
        sys.modules[name] = module
        
        tfname = tempfile.mktemp('.py')
        try:
            f = open(tfname, 'w')
        except (OSError, IOError):
            return module
            
        f.write(code)
        f.close()
        py_compile.compile(tfname, '%s%spyc' %
(os.path.splitext(filename)[0], os.extsep))
        os.remove(tfname)
        return module




More information about the Python-list mailing list