simple import hook

Andrea Crotti andrea.crotti.0 at gmail.com
Thu Nov 10 10:44:29 EST 2011


So I would really like to accomplish the following:
run a program normally and keep track of all the imports that were 
actually done.

I studied the PEP 302, but I'm still a bit confused about how to do it.

I thought that instead of implementing everything I could just record 
the request
and then delegate to the "imp" module, so I did this:

class MyLoader(object):
     """
     Loader object
     """

     def __init__(self):
         self.loaded = set()

     def find_module(self, module_name, package=None):
         print("requesting %s" % module_name)
         self.loaded.add(module_name)
         return self

     def load_module(self, fullname):
         #XXX: the find_module is actually doing nothing, since
         # everything is delegated to the "imp" module
         fp, pathname, stuff = imp.find_module(fullname)
         imp.load_module(fullname, fp, pathname, stuff)

     myl = MyLoader()
     sys.meta_path.append(myl)
     try:
         import random
         import os
         print(random.random())



Which doesn't work, and very strangely it doesn't even look deterministic!
Sometimes it stops at first import sometimes it's able to do a few of them.
How can that be?

And how could I do solve my problem?



More information about the Python-list mailing list