Restrict import to specific path, without restricting the imported module's path

StackOverflow https://stackoverflow.com/questions/13100748

  •  14-07-2021
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول

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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top