### Get Resource Data from a Package using pkgutil.get_data Source: https://docs.python.org/3/library/pkgutil.html Retrieves the content of a resource file within a package. This function is a wrapper for the loader's get_data API and supports resources from various locations, including zip files. It returns binary data. ```python import pkgutil # Example usage (replace _package_ and _resource_ with actual values) # data = pkgutil.get_data(_package_, _resource_) # if data: # print(f"Resource data retrieved: {len(data)} bytes") # else: # print("Resource not found or loader does not support get_data.") ``` ```python d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() ``` -------------------------------- ### pkgutil.get_data(_package_, _resource_) Source: https://docs.python.org/3/library/pkgutil.html Retrieves binary data for a specified resource within a package. It acts as a wrapper for the loader's `get_data` API and supports resources from various locations, including zip files. The function returns the resource content as a binary string or `None` if the package or resource cannot be found or loaded. ```APIDOC ## pkgutil.get_data(_package_, _resource_) ### Description Get a resource from a package. This is a wrapper for the loader `get_data` API. The _package_ argument should be the name of a package, in standard module format (`foo.bar`). The _resource_ argument should be in the form of a relative filename, using `/` as the path separator. The function returns a binary string that is the contents of the specified resource. This function uses the loader method `get_data()` to support modules installed in the filesystem, but also in zip files, databases, or elsewhere. ### Warning This function is intended for trusted input. It does not verify that _resource_ “belongs” to _package_. If you use a user-provided _resource_ path, consider verifying it. For example, require an alphanumeric filename with a known extension, or install and check a list of known resources. If the package cannot be located or loaded, or it uses a loader which does not support `get_data`, then `None` is returned. In particular, the loader for namespace packages does not support `get_data`. ### See also The `importlib.resources` module provides structured access to module resources. ``` -------------------------------- ### List Submodules of a Package using pkgutil.walk_packages Source: https://docs.python.org/3/library/pkgutil.html Use this to list all submodules of a given package. It requires the package's __path__ and __name__ attributes. ```python import pkgutil import ctypes for importer, modname, ispkg in pkgutil.walk_packages(ctypes.__path__, ctypes.__name__ + '.'): print(f"Importer: {importer}, Module Name: {modname}, Is Package: {ispkg}") ``` -------------------------------- ### Extend Package Path with `pkgutil.extend_path` Source: https://docs.python.org/3/library/pkgutil.html Use this in a package's `__init__.py` to allow different parts of a logical package to be distributed as multiple directories. It searches for subdirectories matching the package name and `*.pkg` files. ```python from pkgutil import extend_path __path__ = extend_path(__path__, __name__) ``` -------------------------------- ### walk_packages Source: https://docs.python.org/3/library/pkgutil.html Recursively yields ModuleInfo for all modules on a given path, or all accessible modules if path is None. ```APIDOC ## walk_packages(path = None, prefix = '', onerror = None) ### Description Yields `ModuleInfo` for all modules recursively on `path`, or, if `path` is `None`, all accessible modules. `path` should be either `None` or a list of paths to look for modules in. `prefix` is a string to output on the front of every module name on output. Note that this function must import all _packages_ (not all modules!) on the given `path`, in order to access the `__path__` attribute to find submodules. `onerror` is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package. If no `onerror` function is supplied, `ImportError`s are caught and ignored, while all other exceptions are propagated, terminating the search. ### Parameters #### Query Parameters - **path** (list or None, optional) - A list of paths to look for modules in, or None to search all accessible modules. Defaults to None. - **prefix** (str, optional) - A string to prepend to module names. Defaults to ''. - **onerror** (function, optional) - A function to call if an exception occurs during package import. Defaults to None. ### Yields - `ModuleInfo` objects for each module found recursively. ``` -------------------------------- ### List All Accessible Modules with `pkgutil.walk_packages` Source: https://docs.python.org/3/library/pkgutil.html This function recursively yields `ModuleInfo` for all modules accessible on `sys.path`. It imports packages to find submodules, and an `onerror` callback can handle import errors. ```python # list all modules python can access walk_packages() ``` -------------------------------- ### iter_modules Source: https://docs.python.org/3/library/pkgutil.html Yields ModuleInfo for all submodules on a given path, or all top-level modules on sys.path if path is None. ```APIDOC ## iter_modules(path = None, prefix = '') ### Description Yields `ModuleInfo` for all submodules on `path`, or, if `path` is `None`, all top-level modules on `sys.path`. `path` should be either `None` or a list of paths to look for modules in. `prefix` is a string to output on the front of every module name on output. Note: Only works for a finder which defines an `iter_modules()` method. This interface is non-standard, so the module also provides implementations for `importlib.machinery.FileFinder` and `zipimport.zipimporter`. ### Parameters #### Query Parameters - **path** (list or None, optional) - A list of paths to look for modules in, or None to search sys.path. Defaults to None. - **prefix** (str, optional) - A string to prepend to module names. Defaults to ''. ### Yields - `ModuleInfo` objects for each submodule found. ``` -------------------------------- ### get_importer Source: https://docs.python.org/3/library/pkgutil.html Retrieves a module finder for a given path item. The finder is cached in sys.path_importer_cache if newly created. ```APIDOC ## get_importer(path_item) ### Description Retrieve a finder for the given `path_item`. The returned finder is cached in `sys.path_importer_cache` if it was newly created by a path hook. The cache (or part of it) can be cleared manually if a rescan of `sys.path_hooks` is necessary. ### Parameters #### Path Parameters - **path_item** (str) - The path item to get a finder for. ### Returns - A finder object for the given path item. ``` -------------------------------- ### extend_path Source: https://docs.python.org/3/library/pkgutil.html Extends the search path for modules that make up a package. It adds subdirectories matching the package name from sys.path and processes *.pkg files. ```APIDOC ## extend_path(path, name) ### Description Extend the search path for the modules which comprise a package. Intended use is to place the following code in a package’s `__init__.py`: ```python from pkgutil import extend_path __path__ = extend_path(__path__, __name__) ``` For each directory on `sys.path` that has a subdirectory that matches the package name, add the subdirectory to the package’s `__path__`. This is useful if one wants to distribute different parts of a single logical package as multiple directories. It also looks for `*.pkg` files beginning where `*` matches the `name` argument. This feature is similar to `*.pth` files (see the `site` module for more information), except that it doesn’t special-case lines starting with `import`. A `*.pkg` file is trusted at face value: apart from skipping blank lines and ignoring comments, all entries found in a `*.pkg` file are added to the path, regardless of whether they exist on the filesystem (this is a feature). If the input path is not a list (as is the case for frozen packages) it is returned unchanged. The input path is not modified; an extended copy is returned. Items are only appended to the copy at the end. It is assumed that `sys.path` is a sequence. Items of `sys.path` that are not strings referring to existing directories are ignored. Unicode items on `sys.path` that cause errors when used as filenames may cause this function to raise an exception (in line with `os.path.isdir()` behavior). ### Parameters #### Path Parameters - **path** (list) - The current package path. - **name** (str) - The name of the package. ### Returns - A new list representing the extended package path. ``` -------------------------------- ### iter_importers Source: https://docs.python.org/3/library/pkgutil.html Yields finder objects for a specified module name. If no name is given, yields all registered top-level finders. ```APIDOC ## iter_importers(fullname = '') ### Description Yield finder objects for the given module name. If `fullname` contains a `.`, the finders will be for the package containing `fullname`, otherwise they will be all registered top level finders (i.e. those on both `sys.meta_path` and `sys.path_hooks`). If the named module is in a package, that package is imported as a side effect of invoking this function. If no module name is specified, all top level finders are produced. ### Parameters #### Query Parameters - **fullname** (str, optional) - The full module name. Defaults to ''. ### Yields - Finder objects. ``` -------------------------------- ### pkgutil.resolve_name(_name_) Source: https://docs.python.org/3/library/pkgutil.html Resolves a given name string to a Python object. The name can be in a dotted format representing a module or an object within a module. This function is useful for dynamically accessing objects based on their string representation. ```APIDOC ## pkgutil.resolve_name(_name_) ### Description Resolve a name to an object. This functionality is used in numerous places in the standard library (see bpo-12915) - and equivalent functionality is also in widely used third-party packages such as setuptools, Django and Pyramid. It is expected that _name_ will be a string in one of the following formats, where W is shorthand for a valid Python identifier and dot stands for a literal period in these pseudo-regexes: * `W(.W)*` * `W(.W)*:(W(.W)*)?` The first form is intended for backward compatibility only. It assumes that some part of the dotted name is a package, and the rest is an object somewhere within that package, possibly nested inside other objects. Because the place where the package stops and the object hierarchy starts can’t be inferred by inspection, repeated attempts to import must be done with this form. In the second form, the caller makes the division point clear through the provision of a single colon: the dotted name to the left of the colon is a package to be imported, and the dotted name to the right is the object hierarchy within that package. Only one import is needed in this form. If it ends with the colon, then a module object is returned. The function will return an object (which might be a module), or raise one of the following exceptions: `ValueError` – if _name_ isn’t in a recognised format. `ImportError` – if an import failed when it shouldn’t have. `AttributeError` – If a failure occurred when traversing the object hierarchy within the imported package to get to the desired object. ### Added in version 3.9 ``` -------------------------------- ### Resolve a Name to an Object using pkgutil.resolve_name Source: https://docs.python.org/3/library/pkgutil.html Resolves a string name to a Python object. It supports two formats: 'W(.W)*' for backward compatibility and 'W(.W)*:W(.W)*' for explicit package/object division. This function can raise ValueError, ImportError, or AttributeError. ```python import pkgutil # Example usage (replace 'module.object' with an actual name) # try: # obj = pkgutil.resolve_name('module.object') # print(f"Resolved object: {obj}") # except (ValueError, ImportError, AttributeError) as e: # print(f"Error resolving name: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.