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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.