Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do a load a python package resource from the current distribution using pkg_resources?

I have a Python package with some css stylesheets which I have included as resources like so:

from setuptools import setup
setup(
    package_data={
        'my.package.name': ['*.css']
    }
    # ...
)

I would now like to load one of these included resources as a string. What is the best way to load a resource from the current package?

I see that the pkg_resources.Distribution object has a get_resource_string() method, but I am stuck on how to use this: How do I get a Distribution object for the current package?

like image 420
Daniel Fortunov Avatar asked Mar 19 '12 09:03

Daniel Fortunov


People also ask

What is Pkg_resources Python?

pkg_resources is a module used to find and manage Python package/version dependencies and access bundled files and resources, including those inside of zipped . egg files.

How do I include a file in a Python package?

Place the files that you want to include in the package directory (in our case, the data has to reside in the roman/ directory). Add the field include_package_data=True in setup.py. Add the field package_data={'': [... patterns for files you want to include, relative to package dir...]} in setup.py .


1 Answers

There is a convenience method at the top level of pkg_resources for this:

import pkg_resources
my_data = pkg_resources.resource_string(__name__, "my_style.css")
like image 179
Daniel Fortunov Avatar answered Nov 02 '22 07:11

Daniel Fortunov