Reputation: 50497
Is it possible to import a module from a specific directory, without affecting the import path of the imported module?
If I was to temporarily replace sys.path
with the desired directory, the imported module would not be able to import anything outside of that directory.
I don't want to just prepend sys.path
with the directory, because I don't want importing to fall back to another source.
Upvotes: 4
Views: 653
Reputation: 34260
The standard library's imp module allows you to search a list of paths to find and import a module without altering sys.path
. For example:
import imp
search_paths = [path_to_spam]
modfile, modpath, description = imp.find_module('spam', search_paths)
with modfile:
spam = imp.load_module('spam', modfile, modpath, description)
Upvotes: 4