2 pkgdata is a simple, extensible way for a package to acquire data file
5 The getResource function is equivalent to the standard idioms, such as
6 the following minimal implementation::
10 def getResource(identifier, pkgname=__name__):
11 pkgpath = os.path.dirname(sys.modules[pkgname].__file__)
12 path = os.path.join(pkgpath, identifier)
13 return file(os.path.normpath(path), mode='rb')
15 When a __loader__ is present on the module given by __name__, it will defer
16 getResource to its get_data implementation and return it as a file-like
17 object (such as StringIO).
22 from cStringIO
import StringIO
24 def get_resource(identifier
, pkgname
=__name__
):
26 Acquire a readable object for a given package name and identifier.
27 An IOError will be raised if the resource can not be found.
30 mydata = get_esource('mypkgdata.jpg').read()
32 Note that the package name must be fully qualified, if given, such
33 that it would be found in sys.modules.
35 In some cases, getResource will return a real file object. In that
36 case, it may be useful to use its name attribute to get the path
37 rather than use it as a file-like object. For example, you may
38 be handing data off to a C API.
41 mod
= sys
.modules
[pkgname
]
42 fn
= getattr(mod
, '__file__', None)
44 raise IOError("%r has no __file__!")
45 path
= os
.path
.join(os
.path
.dirname(fn
), identifier
)
46 loader
= getattr(mod
, '__loader__', None)
47 if loader
is not None:
49 data
= loader
.get_data(path
)
54 return file(os
.path
.normpath(path
), 'rb')