我不明白pkg_resource.resource_filename()到底是如何工作的,以及它的参数是什么。我在网上搜索了很多,但他们的官方文档并没有很好地涵盖它。有人能解释一下吗?
发布于 2019-03-07 06:06:31
这里有几个例子。我在一个旧环境中安装了轮子0.24:
pkg_resources.resource_filename('spamalot', "wheel/__init__.py")
ImportError: No module named spamalot
第一个参数必须是可导入的。第二个参数应该是/分隔的相对路径,包括使用\分隔路径的系统。
In [27]: pkg_resources.resource_filename('distutils', "wheel/__init__.py")
Out[27]: '/opt/pyenv/lib64/python2.7/distutils/wheel/__init__.py'
如果它是可导入的,您将在导入的名称中获得一个路径。在这种情况下,文件是否存在并不重要。
In [28]: pkg_resources.resource_filename(pkg_resources.Requirement.parse('wheel>0.23.0'), "core.py")
Out[28]: '/opt/pyenv/lib/python2.7/site-packages/core.py'
你可以通过一个要求,它会检查你是否真的安装了它。现在,路径是相对于安装目录的,而不是相对于wheel
包的。
In [29]: pkg_resources.resource_filename(pkg_resources.Requirement.parse('wheel>0.27.0'), "core.py")
VersionConflict: (wheel 0.24.0 (/opt/pyenv/lib/python2.7/site-packages), Requirement.parse('wheel>0.27.0'))
如果没有安装该要求,它将会报错。
Requirement
特性存在的一个原因是因为路径上可能有同一个包的多个版本的鸡蛋,pkg_resources
会添加请求的版本,但是这个特性已经不再使用了。
这些示例非常简单,但是如果您的资源位于.zip
文件中或任何其他受支持的导入位置(可以挂钩Python的导入系统,以便导入来自任何地方-如果安装了正确的挂钩,则sqlite数据库、网络、...和resource_filename应该能够处理这些内容),则resource_filename
也可以工作。
https://stackoverflow.com/questions/55032454
复制相似问题