Add a single module to Python's import search

2019-07-18 12:53发布

问题:

If I set PYTHONPATH to some path /path/to/modules/, then the path is appended to sys.path and I can import modules/packages contained in /path/to/modules/.

However, if I only want access to a single module/package, then adding /path/to/modules/mymod.py or /path/to/modules/mypackage/ to sys.path does not work.

So is there a way to add only a single module/package to the import search path, rather than adding the entire parent directory?

I am asking because I need to import a single package installed under /usr/lib/python3/dist-packages/ from within a virtual environment, and I would prefer not to give the virtual environment access to all of the modules/packages installed under that path. (The package has a complicated build process and cannot be easily installed to a virtual environment.)

I have read https://stackoverflow.com/a/67692/ but I am wondering if it's possible to actually include the package in the import search path, so that the package (and the modules it contains) can be imported normally.

回答1:

There is no such way. If you want to import a module you have to add its parent directory to sys.path. But you can remove it later:

sys.path.append('/usr/lib/python3/dist-packages/')
import mypackage
del sys.path[-1]