simple import hook

Discussion in 'Python' started by Andrea Crotti, Nov 10, 2011.

  1. 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?
    Andrea Crotti, Nov 10, 2011
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Noam Raphael
    Replies:
    0
    Views:
    274
    Noam Raphael
    Jun 21, 2004
  2. Torsten Mohr

    import hook, overwrite import?

    Torsten Mohr, Jan 26, 2005, in forum: Python
    Replies:
    2
    Views:
    431
    Steve Holden
    Jan 27, 2005
  3. Replies:
    6
    Views:
    641
    Fuzzyman
    Jul 11, 2005
  4. Jeremy Sanders

    import hook

    Jeremy Sanders, Jun 11, 2006, in forum: Python
    Replies:
    4
    Views:
    378
    Jeremy Sanders
    Jun 18, 2006
  5. Andrea Crotti
    Replies:
    0
    Views:
    146
    Andrea Crotti
    Jan 19, 2012
Loading...

Share This Page