Restrict import to specific path, without restricting the imported module's path
Question
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.
Solution
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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow