0
package_path = '/home/foo/bar/'
module_class = 'hello.World'
method = 'something'

first, i want to import the hello module what it is inside of the package_path (/home/foo/bar/)

then, i must instantiate the class World at this module

and finally i should run the something() method on the new world_instance_object

any idea for do that?

Thank you so much!

fj123x
  • 6,904
  • 12
  • 46
  • 58
  • this can be duplicate for http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – oleg Sep 20 '13 at 21:45
  • any way for import a package (not module) from path string and then, import the module.Class for them? – fj123x Sep 20 '13 at 22:14
  • package and module are imported same way. class is module attribute, method is class atribute. Use `getattr` for obtaining object's attribute – oleg Sep 20 '13 at 22:17

1 Answers1

1

To avoid having to manipulate sys.path and to keep all the extra modules you import from cluttering up sys.modules, I'd suggest using execfile() for this. Something like this (untested code):

import os.path

def load_and_call(package_path, module_class, method_name):
    module_name, class_name = module_class.split(".")
    module_globals = {}
    execfile(os.path.join(package_path, module_name + ".py"), module_globals)
    return getattr(module_globals[class_name](), method_name, lambda: None)()

You could add some code to cache the parsed objects using a dictionary, if a file will be used more than once (again, untested):

def load_and_call(package_path, module_class, method_name, _module_cache={}):
    module_name, class_name = module_class.split(".")
    py_path = os.path.join(package_path, module_name + ".py")
    module_globals = _module_cache.setdefault(py_path, {})
    if not module_globals:
        execfile(py_path, module_globals)
    return getattr(module_globals[class_name](), method_name, lambda: None)()
kindall
  • 178,883
  • 35
  • 278
  • 309