如何使用源代码中 package_data 中的数据? [英] How do I use data in package_data from source code?

查看:23
本文介绍了如何使用源代码中 package_data 中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 setup.py 中,我像这样指定了 package_data:

In setup.py, I have specified package_data like this:

packages=['hermes'],
package_dir={'hermes': 'hermes'},
package_data={'hermes': ['templates/*.tpl']},

而我的目录结构大致是

hermes/
 |
 | docs/
 | ...
 | hermes/
    | 
    | __init__.py
    | code.py
    | templates
        |
        | python.tpl
 |
 | README
 | setup.py

问题是我需要在我的源代码中使用模板目录中的文件,这样我才能写出 python 代码(这个项目是一个解析器生成器).我似乎无法弄清楚如何从我的代码中正确包含和使用这些文件.有什么想法吗?

The problem is that I need to use files from the templates directory in my source code so I can write out python code (this project is a parser generator). I can't seem to figure out how to properly include and use these files from my code. Any ideas?

推荐答案

标准 pkgutil 模块的 get_data() 函数 将计算您的数据相对于您的包的路径,并通过用于导入 hermes 的任何模块加载器 Python 为您检索数据 包:

import pkgutil
data = pkgutil.get_data('hermes', 'templates/python.tpl')

当然,在某些情况下,您可以使用从 hermes.__file__ 计算的路径读取数据,但是如果您计划分发您的项目,请考虑它可能以不同的方式安装在最终用户的机器:作为纯文件,部署在压缩的蛋档案等中.在后一种情况下,你的 hermes 模块将被 Python 使用 zipimporter 导入,防止你从做一个正常的open(path).read():

Of course in certain cases you could just read your data using a path calculated from hermes.__file__, but if you plan to distribute your project, consider that it may be installed in different ways on the end user's machine: as plain files, deployed in a zipped egg archive, etc. In the latter case, your hermes module will have been imported by Python using a zipimporter, preventing you from doing a normal open(path).read():

>>> import hermes
>>> hermes.__loader__
<zipimporter object "/home/pat/.cascade/virt/foo/lib/python2.6/site-packages/foo-0.0.0-py2.6.egg">

如果您同意在 distribute 代码库上添加运行时依赖项,您可能需要考虑查看 pkg_resources 模块,它可以为您提供相同的结果,但增加了其他功能.

If you're okay with adding a runtime dependency on the distribute codebase, you may want to consider looking at the pkg_resources module, which can give you the same result but adds other capabilities.

import pkg_resources
data = pkg_resources.resource_string('hermes', 'templates/python.tpl')

这篇关于如何使用源代码中 package_data 中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆