软件包中的Python pkg_resources和文件访问 [英] Python pkg_resources and file access in packages
问题描述
我正在构建我的第一个python软件包(然后通过pip安装),我需要使用一些非python文件.在这些答案中,解释了我应该使用pkg_resources
函数.但是我不知道一个可行的例子.假设我有这个项目结构:
I'm building my first python package (which I then install with pip) and I need to use some non-python files. In these answers, it is explained that I should use the pkg_resources
function. But I can't figure out a working example. Let say I have this project structure:
package_name/
----data/
--------image.png
----package_name/
--------__init__.py
--------file.py
----setup.py
----MANIFEST.in
----conf.yml
现在我要从file.py
访问conf.yml
和image.png
.我应该如何进行:
Now I want to access conf.yml
and image.png
from file.py
. How should I proceed in:
- file.py吗?
- setup.py?
- MANIFEST.in吗?
推荐答案
访问这些文件的最简单方法是将其包含在MANIFEST.in
The simplest way to access these files would be to include in MANIFEST.in
global-include *.png
global-include *.yml
MANIFEST.in仅将文件用于源代码分发,而setup.py将包含用于二进制/车轮分发的文件,因此为了安全起见,在setup.py内部
MANIFEST.in will only use files for a source distribution though, while setup.py will include files for binary/wheel distributions so just to be safe, inside of your setup.py
include_package_data = True,
package_data = {
'' : ['*.png'],
'' : ['*.yml'],
}
然后您可以从file.py中引用特定文件
Then you can reference the specific file like so from file.py
from pkg_resources import resource_string
def foo():
pngfile = resource_string(__name__, 'data/image.png')
ymlfile = resource_string(__name__, 'conf.yml')
请注意,我是如何为png文件指定目录的.
Notice how for the png file I've specified the directory.
此解决方案也不考虑您可能要排除的扩展名相同的文件,但是可以通过排除或指定文件名而不是使用星号来轻松处理这些文件.
This solution also does not account for files of the same extension which you may want to exclude, but those could easily be taken care of with exclude or specifying filenames rather than using the asterisk.
我知道有些问题很容易被认为是重复的,但是我也很难得到一个可行的例子,经过一番努力之后,我设法使一些事情得以解决.
I know there are questions that could easily be considered duplicates, but I had trouble getting a workable example as well and after a good while badgering away myself I managed to get something to work, and this was it.
这篇关于软件包中的Python pkg_resources和文件访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!