Ayu*_*ain 7 python pkg-resources
我不明白 pkg_resource.resource_filename() 到底是如何工作的以及它的参数是什么。我在网上搜索了很多,但他们的官方文档并没有很好地涵盖它。有人可以解释一下吗?
这里有一些例子。我在旧环境中安装了wheel 0.24:
pkg_resources.resource_filename('spamalot', "wheel/__init__.py")
ImportError: No module named spamalot
Run Code Online (Sandbox Code Playgroud)
第一个参数必须是重要的。第二个参数应该是一个以 / 分隔的相对路径,包括在使用 \ 分隔路径的系统上。
In [27]: pkg_resources.resource_filename('distutils', "wheel/__init__.py")
Out[27]: '/opt/pyenv/lib64/python2.7/distutils/wheel/__init__.py'
Run Code Online (Sandbox Code Playgroud)
如果它是可导入的,您将在导入的名称中获得一个路径。在这种情况下,文件是否存在并不重要。
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'
Run Code Online (Sandbox Code Playgroud)
您可以通过一个要求,它会检查您是否确实安装了它。现在路径是相对于安装目录而不是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'))
Run Code Online (Sandbox Code Playgroud)
如果未安装该要求,它将抱怨。
该功能存在的原因之一Requirement是因为路径上同一包的多个版本可能有鸡蛋,并且pkg_resources会添加请求的版本,但该功能不再被广泛使用。
这些示例非常简单,但resource_filename如果您的资源位于.zip文件或任何其他受支持的导入位置内(可以挂接 Python 的导入系统,以便导入来自任何地方 - sqlite 数据库、网络等,那么它们也将起作用)如果安装了正确的钩子,resource_filename 应该能够使用这些。)