grass.tools package¶
Submodules¶
grass.tools.session_tools module¶
The module provides an API to use GRASS tools (modules) as Python functions
- class grass.tools.session_tools.Tools(*, session=None, env=None, overwrite=None, verbose=None, quiet=None, superquiet=None, errors=None, capture_output=True, capture_stderr=None, consistent_return_value=False)[source]¶
Bases:
object
Use GRASS tools through function calls (experimental)
GRASS tools (modules) can be executed as methods of this class. This API is experimental in version 8.5 and is expected to be stable in version 8.6.
The tools can be used in an active GRASS session (this skipped when writing a GRASS tool):
>>> import grass.script as gs >>> gs.create_project("xy_project") >>> session = gs.setup.init("xy_project")
Multiple tools can be accessed through a single Tools object:
>>> from grass.tools import Tools >>> tools = Tools(session=session) >>> tools.g_region(rows=100, cols=100) >>> tools.r_random_surface(output="surface", seed=42)
For tools outputting JSON, the results can be accessed directly:
>>> print("cells:", tools.g_region(flags="p", format="json")["cells"]) cells: 10000
Resulting text or other output can be accessed through attributes of the ToolResult object:
>>> tools.g_region(flags="p").text
Text inputs, when a tool supports standard input (stdin), can be passed as io.StringIO objects:
>>> from io import StringIO >>> tools.v_in_ascii( ... input=StringIO("13.45,29.96,200"), output="point", separator="," ... )
The Tools object can be used as a context manager:
>>> with Tools(session=session) as tools: ... tools.g_region(rows=100, cols=100)
A tool can be accessed via a function with the same name as the tool. Alternatively, it can be called through one of the run or call functions. The run function provides convenient functionality for handling tool parameters, while the call function simply executes the tool. Both take tool parameters as keyword arguments. Each function has a corresponding variant which accepts a list of strings as parameters (run_cmd and call_cmd). When a tool is run using the function corresponding to its name, the run function is used in the background.
Raster input and outputs can be NumPy arrays:
>>> import numpy as np >>> tools.g_region(rows=2, cols=3) >>> slope = tools.r_slope_aspect(elevation=np.ones((2, 3)), slope=np.ndarray) >>> tools.r_grow( ... input=np.array([[1, np.nan, np.nan], [np.nan, np.nan, np.nan]]), ... radius=1.5, ... output=np.ndarray, ... ) array([[1., 1., 0.], [1., 1., 0.]])
The input array’s shape and the computational region rows and columns need to match. The output array’s shape is determined by the computational region.
When multiple outputs are returned, they are returned as a tuple:
>>> (slope, aspect) = tools.r_slope_aspect( ... elevation=np.ones((2, 3)), slope=np.array, aspect=np.array ... )
To access the arrays by name, e.g., with a high number of output arrays, the standard result object can be requested with consistent_return_value:
>>> tools = Tools(session=session, consistent_return_value=True) >>> result = tools.r_slope_aspect( ... elevation=np.ones((2, 3)), slope=np.array, aspect=np.array ... )
The result object than includes the arrays under the arrays attribute where they can be accessed as attributes by names corresponding to the output parameter names:
>>> slope = result.arrays.slope >>> aspect = result.arrays.aspect
Using consistent_return_value=True is also advantageous to obtain both arrays and text outputs from the tool as the result object has the same attributes and functionality as without arrays:
>>> result.text ''
If session is provided and has an env attribute, it is used to execute tools. If env is provided, it is used to execute tools. If both session and env are provided, env is used to execute tools and session is ignored. However, session and env interaction may change in the future.
If overwrite is provided, a an overwrite is set for all the tools. When overwrite is set to False, individual tool calls can set overwrite to True. If overwrite is set in the session or env, it is used. Note that once overwrite is set to True globally, an individual tool call cannot set it back to False.
If verbose, quiet, superquiet is set to True, the corresponding verbosity level is set for all the tools. If one of them is set to False and the environment has the corresponding variable set, it is unset. The values cannot be combined. If multiple ones are set to True, the most verbose one wins.
In case a tool run fails, indicating that by non-zero return code, grass.exceptions.CalledModuleError exception is raised by default. This can be changed by passing, e.g., errors=”ignore”. The errors parameter is passed to the grass.script.handle_errors function which determines the specific behavior.
Text outputs from the tool are captured by default, both standard output (stdout) and standard error output (stderr). Both will be part of the result object returned by each tool run. Additionally, the standard error output will be included in the exception message. When capture_output is set to False, outputs are not captured in Python as values and go where the Python process outputs go (this is usually clear in command line, but less clear in a Jupyter notebook). When capture_stderr is set to True, the standard error output is captured and included in the exception message even if capture_outputs is set to False.
A tool call will return a result object if the tool produces standard output (stdout) and None otherwise. If consistent_return_value is set to True, a call will return a result object even without standard output (stdout and text attributes of the result object will evaluate to False). This is advantageous when examining the stdout or text attributes directly, or when using the returncode attribute in combination with errors=”ignore”. Additionally, this can be used to obtain both NumPy arrays and text outputs from a tool call.
If env or other Popen arguments are provided to one of the tool running functions, the constructor parameters except errors are ignored.
- call(tool_name_: str, /, **kwargs)[source]¶
Run a tool by specifying its name as a string and parameters.
The parameters tool are tool name as a string and parameters as keyword arguments. The keyword arguments may include an argument flags which is a string of one-character tool flags.
The function will directly execute the tool without any major processing of the parameters, but numbers, lists, and tuples will still be translated to strings for execution.
- Parameters:
tool_name – name of a GRASS tool
**kwargs –
tool parameters
- call_cmd(command, tool_kwargs=None, input=None, **popen_options)[source]¶
Run a tool by passing its name and parameters as a list of strings.
The function is similar to
subprocess.run()
but with different defaults and return value.- Parameters:
command – list of strings to execute as the command
tool_kwargs – named tool arguments used for error reporting (experimental)
input – text input for the standard input of the tool
**popen_options –
additional options for
subprocess.Popen()
- run(tool_name_: str, /, **kwargs)[source]¶
Run a tool by specifying its name as a string and parameters.
The parameters tool are tool name as a string and parameters as keyword arguments. The keyword arguments may include an argument flags which is a string of one-character tool flags.
The function may perform additional processing on the parameters.
- Parameters:
tool_name – name of a GRASS tool
kwargs – tool parameters
- run_cmd(command: list[str], *, input: str | bytes | None = None, tool_kwargs: dict | None = None, **popen_options)[source]¶
Run a tool by passing its name and parameters a list of strings.
The function may perform additional processing on the parameters.
- Parameters:
command – list of strings to execute as the command
input – text input for the standard input of the tool
tool_kwargs – named tool arguments used for error reporting (experimental)
**popen_options –
additional options for
subprocess.Popen()
grass.tools.support module¶
The module provides support functionality for calling GRASS tools (modules) as Python functions.
Do not use this module directly unless you are developing GRASS or its wrappers. In that case, be prepared to update your code if this module changes. This module may change between releases.
- class grass.tools.support.ParameterConverter[source]¶
Bases:
object
Converts parameter values to strings and facilitates flow of the data.
- process_parameters(kwargs)[source]¶
Converts high level parameter values to strings.
Converts io.StringIO to dash and stores the string in the stdin attribute. Replaces NumPy arrays by temporary raster names and stores the arrays. Replaces NumPy array types by temporary raster names.
Temporary names are accessible in the temporary_rasters attribute and need to be cleaned. The functions translate_objects_to_data and translate_data_to_objects need to be called before and after the computation to do the translations from NumPy arrays to GRASS data and from GRASS data to NumPy arrays.
Simple type conversions from numbers and iterables to strings are expected to be done by lower level code.
- class grass.tools.support.ToolFunctionResolver(*, run_function, env, allowed_prefix=None)[source]¶
Bases:
object
- get_tool_name(name, exception_type)[source]¶
Parse attribute to GRASS display module. Attribute should be in the form ‘tool_name’. For example, ‘r.info’ is called with ‘r_info’.
- suggest_tools(text)[source]¶
Suggest matching tool names based on provided text.
The first five tools matching the condition are returned, so this always returns at most five names, but it may not be the best matches. The returned names are sorted alphabetically (not by priority). This specific behavior may change in the future versions.
- class grass.tools.support.ToolResult(*, name, command, kwargs, returncode, stdout, stderr)[source]¶
Bases:
object
Result returned after executing a tool
- property comma_items: list¶
Text output read as comma-separated list
Empty or no output results in an empty list.
- property json: dict¶
Text output read as JSON
This returns the nested structure of dictionaries and lists or fails when the output is not JSON.
- property keyval: dict¶
Text output read as key-value pairs separated by equal signs
If possible, values are converted to int or float. Empty values result in an empty string value (there is no recognized null value). Empty or no output results in an empty dictionary.
- property space_items: list¶
Text output read as whitespace-separated list
Empty or no output results in an empty list.