Question about import and sys.path
frank at chagford.com
Wed Nov 29 06:53:52 CET 2006
Rob Wolfe wrote:
> Frank Millman wrote:
> > Hi all
> > However, I want the ability to have duplicate program names stored in
> > different subdirectories. At the time of selecting the menu option I
> > know which company is active, so I know which directory I want to run
> > the program from, but there does not seem to be a way to tell 'import'
> > to import from a particular directory.
> I suggest to use module `imp`.
> For example:
> I assume paths like this:
> the module in the company1 subdirectory:
> # prog1
> class SomeClass(object):
> def test(self):
> return "%s: %s" % (__file__, self.__class__.__name__)
> and the module with your menu could look like this:
> # importer.py
> def get_class(classname, impname, company):
> fp, pathname, description = imp.find_module(impname, [company])
> m = imp.load_module(impname, fp, pathname, description)
> return getattr(m, classname)
> obj = get_class("SomeClass", "prog1", "company1")()
> print obj.test()
Perfect. Thanks very much, Rob.
One small point. The docs have the following warning -
"Important: the caller is responsible for closing the file argument, if
it was not None, even when an exception is raised. This is best done
using a try ... finally statement. "
I have added this to my code.
I wonder if you can avoid this in 2.5 by using the 'with' statement. I
am still using 2.4, so I cannot test. Anyway, your suggestion does
exactly what I want, and it works perfectly.
More information about the Python-list