Coverage for /usr/lib/python3/dist-packages/sympy/utilities/pkgdata.py: 24%
17 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1"""
2pkgdata is a simple, extensible way for a package to acquire data file
3resources.
5The getResource function is equivalent to the standard idioms, such as
6the following minimal implementation::
8 import sys, os
10 def getResource(identifier, pkgname=__name__):
11 pkgpath = os.path.dirname(sys.modules[pkgname].__file__)
12 path = os.path.join(pkgpath, identifier)
13 return open(os.path.normpath(path), mode='rb')
15When a __loader__ is present on the module given by __name__, it will defer
16getResource to its get_data implementation and return it as a file-like
17object (such as StringIO).
18"""
20import sys
21import os
22from io import StringIO
25def get_resource(identifier, pkgname=__name__):
26 """
27 Acquire a readable object for a given package name and identifier.
28 An IOError will be raised if the resource cannot be found.
30 For example::
32 mydata = get_resource('mypkgdata.jpg').read()
34 Note that the package name must be fully qualified, if given, such
35 that it would be found in sys.modules.
37 In some cases, getResource will return a real file object. In that
38 case, it may be useful to use its name attribute to get the path
39 rather than use it as a file-like object. For example, you may
40 be handing data off to a C API.
41 """
43 mod = sys.modules[pkgname]
44 fn = getattr(mod, '__file__', None)
45 if fn is None:
46 raise OSError("%r has no __file__!")
47 path = os.path.join(os.path.dirname(fn), identifier)
48 loader = getattr(mod, '__loader__', None)
49 if loader is not None:
50 try:
51 data = loader.get_data(path)
52 except (OSError, AttributeError):
53 pass
54 else:
55 return StringIO(data.decode('utf-8'))
56 return open(os.path.normpath(path), 'rb')