将单个模块添加到 Python 的导入搜索路径? [英] Add a single module to Python's import search path?

查看:20
本文介绍了将单个模块添加到 Python 的导入搜索路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将 PYTHONPATH 设置为某个路径 /path/to/modules/,则该路径将附加到 sys.path 并且我可以导入/path/to/modules/中包含的模块/包.

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/.

但是,如果我只想访问单个模块/包,则添加 /path/to/modules/mymod.py/path/to/modules/mypackage/sys.path 不起作用.

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?

我之所以这么问是因为我需要从虚拟环境中导入安装在 /usr/lib/python3/dist-packages/ 下的单个包,我不想给虚拟环境访问安装在该路径下的所有模块/包.(该包的构建过程复杂,无法轻松安装到虚拟环境中.)

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.)

我已阅读 https://stackoverflow.com/a/67692/ 但我想知道是否有可能实际上将包包含在导入搜索路径中,这样包(及其包含的模块)就可以正常导入了.

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.

推荐答案

没有这样的方法.如果你想导入一个模块,你必须添加它的sys.path 的父目录.但您可以稍后将其删除:

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]

这篇关于将单个模块添加到 Python 的导入搜索路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆