"dynamical" importing

Fredrik Lundh fredrik at pythonware.com
Wed Oct 19 04:45:30 EDT 2005


Joerg Schuster wrote:

> I need to import modules from user defined paths. I.e. I want to do
> something like:
>
> module_dir = sys.argv[1]
>
> my_path = os.path.join(module_dir, 'bin', 'my_module')
>
> from my_path import my_object
>
> Obviously, it doesn't work this way. How would it work?

some alternatives:

- if you want the modules to remain imported:

    try:
        sys.path.insert(0, os.path.join(module_dir, "bin"))
        module = __import__("my_module")
    finally:
        del sys.path[0]
    object = module.my_object

- if you're only interested in the object:

    namespace = {}
    execfile(os.path.join(module_dir, "bin", "my_module" + ".py"), namespace)
    object = namespace["my_object"]

</F> 






More information about the Python-list mailing list