1

My dev environment is python 2.6, so the importlib.import_module() syntax is not available to me. I'm trying to load a module with a path that is set by a variable; is this even possible in 2.6?

The background is that I'm polling a number of devices from different vendors, so in various directories I have wrapper classes, all with identical methods and return types, which handle the vendor-specific methods for grabbing the data I need. So based on the vendor, I might need to load "platform_foo.stats" or "platform_bar.stats", then call the same methods on the resulting module.

So, something like this, except this is obviously non-working code:

vendor = get_vendor(hostname)
vendor_path = 'platform_%s.stats' % vendor
import vendor_path
stats = vendor_path.stats(constructor_args)

Any ideas?

caw
  • 421
  • 1
  • 3
  • 11

1 Answers1

1

You can use exec() to execute dynamic code in python.

In your case, something like this should do the trick.

vendor = get_vendor(hostname)
vendor_path = 'platform_%s.stats' % vendor
exec("import " + vendor_path)
stats = vendor_path.stats(constructor_args)

I tried this on some built-in modules, and it seemed to work fine.

Moritz
  • 4,565
  • 2
  • 23
  • 21