python使用pkg包,软件包中的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

Now I want to access conf.yml and image.png from file.py. How should I proceed in:

file.py ?

setup.py ?

MANIFEST.in ?

解决方案

The simplest way to access these files would be to include in MANIFEST.in

global-include *.png

global-include *.yml

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'],

}

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')

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值