python:如何递归地将已安装包的资源复制到磁盘
我有一个python包,其中包含一些非python文件(包含在使用清单文件的发行版中),例如:python:如何递归地将已安装包的资源复制到磁盘,python,python-3.8,python-packaging,python-importlib,Python,Python 3.8,Python Packaging,Python Importlib,我有一个python包,其中包含一些非python文件(包含在使用清单文件的发行版中),例如: . ├── example │ ├── __init__.py │ ├── data │ │ ├── __init__.py │ │ ├── text_dir │ │ │ ├── __init__.py │ │ │ └── text-file.txt │ │ └── json_dir │ │ ├── __init__.py │
.
├── example
│ ├── __init__.py
│ ├── data
│ │ ├── __init__.py
│ │ ├── text_dir
│ │ │ ├── __init__.py
│ │ │ └── text-file.txt
│ │ └── json_dir
│ │ ├── __init__.py
│ │ └── json-file.json
│ └── some_code.py
├── README.rst
├── MANIFEST.in
└── setup.py
非python资源正在从some\u code
模块访问,但在某个时候,我还想使用some\u code.py
递归地将数据的内容复制到其他目录。我使用importlib.resources
实现了以下目标(我使用的是python 3.8):
这种方法安全吗?实现这一目标的更好方法是什么
import os
import shutil
import pathlib
from importlib import resources as il_resources
def resource_copy(package, target_root_dir, _pkg_root=None):
pkg_name = package if isinstance(package, str) else package.__name__
if _pkg_root is None:
_pkg_root = pkg_name
subdir = pkg_name[len(_pkg_root) + 1 :].replace(".", os.sep)
target_dir = os.path.join(target_root_dir, subdir)
pathlib.Path(target_dir).mkdir(parents=True, exist_ok=True)
for item in il_resources.contents(package):
if not item.startswith("_"):
if il_resources.is_resource(package, item):
with il_resources.open_text(package, item) as srcf, open(
os.path.join(target_dir, item), "w"
) as dstf:
shutil.copyfileobj(srcf, dstf)
else:
resource_copy(f"{pkg_name}.{item}", target_root_dir, _pkg_root=_pkg_root)
resource_copy("example.data", "/tmp/data_copy")