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. Advertisements

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. Paul Opal
    Replies:
    12
    Views:
    1,228
    Paul Opal
    Oct 11, 2004
  2. JPractitioner
    Replies:
    13
    Views:
    20,615
    Roedy Green
    Feb 24, 2006
  3. Vitali Gontsharuk
    Replies:
    2
    Views:
    756
    Vitali Gontsharuk
    Aug 25, 2005
  4. Noam Raphael
    Replies:
    0
    Views:
    343
    Noam Raphael
    Jun 21, 2004
  5. Torsten Mohr

    import hook, overwrite import?

    Torsten Mohr, Jan 26, 2005, in forum: Python
    Replies:
    2
    Views:
    581
    Steve Holden
    Jan 27, 2005
  6. Replies:
    6
    Views:
    722
    Fuzzyman
    Jul 11, 2005
  7. Jeremy Sanders

    import hook

    Jeremy Sanders, Jun 11, 2006, in forum: Python
    Replies:
    4
    Views:
    471
    Jeremy Sanders
    Jun 18, 2006
  8. Andrea Crotti
    Replies:
    0
    Views:
    238
    Andrea Crotti
    Jan 19, 2012
Loading...