在我尝试分发的包的本地版本中,我有以下代码:
shutil.copytree(WWW_LOCATION, dir_path)
WWW_LOCATION
是我的 python 模块的子文件夹,其中包含一些静态文件和文件夹:
dv
\dv
mytool.py
\www_folder
\somefolders_and_files
setup.py
MANIFEST.in
README.md
LICENSE
setup.cfg
在我的代码中,执行后,我需要将整个文件夹连同一些动态生成的文件一起复制到用户指定的位置。这在本地工作得很好,但我读到要通过 pypi 分发,我必须小心,因为文件可能会被压缩。
This answer解释了如何访问资源中的内容(=在 python 中读取它们),但是,一次只能访问一个文件。将文件夹内容复制到指定位置的安全方法是什么?
最佳答案
“更简单”的解决方案是在您的包设置(setup.py
或 setup.cfg
)中设置 zip_safe=False
,以避免将您的包裹作为压缩鸡蛋安装。由于大多数安装都是使用 pip
完成的,它从不创建压缩的 egg 安装,所以现在遇到压缩包安装的情况越来越少了。
然后您只需要担心有人将包手动压缩到一个 zip 文件中以添加到 sys.path
,您可以选择不支持这种用例。那是另一种形式的压缩包; eggs 是一个可安装项目的 zip 文件(由 pkg_resources
支持)并将它们存储在 sys.path
中列出的目录中。 pkg_resources
只能支持后者,不支持前者。
如果您确实想要支持压缩蛋,那么对于您的具体情况,使用 pkg_resources
API for resource extraction 会更容易。 ,因为虽然它可能“更慢”,但它也支持完整的目录树。来自 resource_filename()
文档:
If the named resource is a directory, then all resources within that directory (including subdirectories) are also extracted.
我会这样使用它:
try:
www_location = pkg_resources.resource_filename("dv", "www_folder")
shutil.copytree(www_location, dir_path)
finally:
pkg_resources.cleanup_resources()
无法通过 pkg_resources
访问直接添加到 sys.path
的 zip 文件中的包内资源。为此,您需要更新的 importlib.resources
module (或者它是 backport ),但此 API 不支持任意目录结构。 importlib.resources.path()
function documenation状态:
package is either a name or a module object which conforms to the
Package
requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory).
(大胆强调我的)。
虽然您可以使用 importlib.resources.contents()
在包中查找目录,您实际上无法访问这些目录的内容,除非它们本身是 Python 包(因此其中有一个 __init__.py
文件)。对于传统的非压缩包,这些函数的实现在使用 importlib.resources.path()
时仍然允许您访问该目录,您不能执行当包包含在 .zip
存档中时也是如此。
importlib.resources
是一个更好的、面向 future 的支持路径。为了支持它,您可以压缩 www_folder
资源树在您的源代码和 wheel 分发版 中,然后使用 with importlib.resources.path("dv", "www_folder.zip") 作为 www_location: www_zip = zipfile.open(www_location)
并将内容从该 zipfile 对象提取到目标位置。
关于python - 从 python 包资源中提取文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58132947/