simple import hook

Andrea Crotti andrea.crotti.0 at gmail.com
Thu Nov 10 12:46:07 EST 2011


On 11/10/2011 05:02 PM, Eric Snow wrote:
>
> Yeah, I'm working on a reference for imports in Python.  They're just
> a little too mysterious relative to the rest of the language.  But
> it's not too helpful yet.  In the meantime...
Yes it's quite mysterious, and it's actually not as hard as it looks..
Anyway I'm glad to say that I reached what I basically wanted.

This script actually compiles the code and runs it, reporting the 
imports done in the end.
Any suggestion is still welcome :)

"""
This script is used to analyse the imports which are actually being done
"""
import argparse
import os
import sys

class CollectImports(object):
     """
     Loader object
     """

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

     def __str__(self):
         return str(self.loaded)

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


if __name__ == '__main__':
     parser = argparse.ArgumentParser(description='analyse the imports 
made')
     parser.add_argument('script')
     parser.add_argument('arguments', nargs='*')

     ns = parser.parse_args()

     progname = ns.script
     sys.path.insert(0, os.path.dirname(progname))

     cl = CollectImports()
     # TODO: maybe we can create a with clause also for this thing
     sys.meta_path.append(cl)

     # TODO: catch the exit signal and present the output
     code = compile(open(progname).read(), progname, 'exec')
     exec(code)
     print("imports done: %s" % str(cl))

> That _is_ pretty strange.
>
> After what I recommended above, are you still getting the wierdness?
> It could just be a side-effect of your use of the imp functions. in
> load_module(), so getting rid of it would help.
>
> What version of Python are you using?  If not 2.7 or 3.2, do you get
> the same problem when you run the code under one of those latest
> versions?
>
> Even when the number of imports is different, are they always in the
> same order?  Highly unlikely, but if you say no then this is extra
> fishy.
>

It was python 2.7 on Arch-linux, but thanks to your suggestions 
everything was actually fixed..



More information about the Python-list mailing list