simple import hook

A

Andrea Crotti

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top