Add a single module to Python's import search path?

只谈情不闲聊 提交于 2020-01-05 02:55:13

问题


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]


来源:https://stackoverflow.com/questions/55316460/add-a-single-module-to-pythons-import-search-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!