Limit the import to a specific path without limiting the path of the imported module

Can I import a module from a specific directory without affecting the import path of the imported module?

If I temporarily replaced sys.path with the desired directory, the imported module would not be able to import anything outside this directory.

I do not want to just add sys.path to the directory, because I do not want the import to return to another source.

+4
source share
1 answer

The standard module imp module allows you to search a list of paths for searching and importing a module without changing sys.path . For instance:

 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) 
+4
source

Source: https://habr.com/ru/post/1442483/


All Articles