是否可以将 .xml 文件嵌入到 conda 包中?

Is it possible to embed a .xml file into a conda package?

我正在为 Python 开发一个 conda 包。 代码的某些行为取决于存储在 .xml 文件中的信息。

我不希望我的包依赖于应与包一起分发且必须由它找到的外部文件。

有没有办法在构建时将此 .xml 文件嵌入到 conda 包中?

谢谢!

如果您正在开发 python 包,解决此问题的一种直接方法是直接使用 setuptools 来传送附加数据:

一个简单的示例项目可能如下所示

example_project
├── Manifest.in
├── data
│   └── data.xml
├── setup.py
└── test_me
    └── __init__.py

各个部分:

data/data.xml(您要随包裹运送的数据):

<data>
    <message>Hello World!</message>
</data>

test_me/__init__.py(读取包中数据的例子):

from pkg_resources import Requirement, resource_filename
import xml.etree.ElementTree as ET
xml_file = resource_filename(Requirement.parse("MyPythonPackageName"), "data/data.xml")

etree = ET.parse(xml_file)
message = etree.getroot()[0].text

Manifest.in(确保在构建分布时包含数据):

include data/data.xml

setup.py(最小设置脚本;请注意我们明确设置 include_package_data):

from setuptools import setup, find_packages

setup(
    name='MyPythonPackageName',
    version='1.0.0',
    author='Me',
    author_email='author@me.com',
    description='additional resource example',
    packages=find_packages(),
    include_package_data=True
)

要测试它,您可以通过 pip install . 从顶级目录安装它,然后使用 python -c "import test_me; print(test_me.message)"

在 xml 中打印消息

然后 conda 包只是安装 python 包,应该不需要额外的步骤。