我如何从源头code package_data使用数据? [英] How do I use data in package_data from source code?

查看:346
本文介绍了我如何从源头code 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

问题是,我需要在我的源代码code从模板目录使用文件,这样我就可以写出来蟒蛇code(这个项目是一个解析器生成)。我似乎无法弄清楚如何正确地包括从我的code使用这些文件。任何想法?

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()功能将计算的路径数据,相对于你的包,并通过任何模块加载Python中导入<$ C $检索数据为您C>爱马仕包:

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

当然,在某些案件中,你可以使用从爱马仕.__文件__ 计算路径刚刚看了你的数据,但如果你打算发布你的项目,认为它可能是安装在最终用户的计算机上不同的方式:纯文本文件,部署在压缩鸡蛋归档等。在后一种情况下,你的爱马仕模块已导入被Python使用 zipimporter ,preventing你做一个正常的打开(路径).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">

如果你没事与添加在分配 codeBase的,你可能要consdider看的<$c$c>pkg_resources模块 ,它可以给你同样的结果,但增加了其他功能。

If you're okay with adding a runtime dependency on the distribute codebase, you may want to consdider 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')

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

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