script package¶
Submodules¶
script.array module¶
Functions to use GRASS 2D and 3D rasters with NumPy.
Usage:
>>> import grass.script as gs
>>> from grass.script import array as garray
>>>
>>> # We create a temporary region that is only valid in this python session
... gs.use_temp_region()
>>> gs.run_command("g.region", n=80, e=120, t=60, s=0, w=0, b=0, res=20, res3=20)
>>>
>>> # Lets create a raster map numpy array
... # based at the current region settings
... map2d_1 = garray.array()
>>>
>>> # Write some data
... for y in range(map2d_1.shape[0]):
... for x in range(map2d_1.shape[1]):
... map2d_1[y, x] = y + x
>>> # Lets have a look at the array
... print(map2d_1)
[[0. 1. 2. 3. 4. 5.]
[1. 2. 3. 4. 5. 6.]
[2. 3. 4. 5. 6. 7.]
[3. 4. 5. 6. 7. 8.]]
>>> # This will write the numpy array as GRASS raster map
... # with name map2d_1
... map2d_1.write(mapname="map2d_1", overwrite=True)
0
>>>
>>> # We create a new array from raster map2d_1 to modify it
... map2d_2 = garray.array(mapname="map2d_1")
>>> # Don't do map2d_2 = map2d_1 % 3
... # because: this will overwrite the internal temporary filename
... map2d_2 %= 3
>>> # Show the result
... print(map2d_2)
[[0. 1. 2. 0. 1. 2.]
[1. 2. 0. 1. 2. 0.]
[2. 0. 1. 2. 0. 1.]
[0. 1. 2. 0. 1. 2.]]
>>> # Write the result as new raster map with name map2d_2
... map2d_2.write(mapname="map2d_2", overwrite=True)
0
>>>
>>> # Here we create a 3D raster map numpy array
... # based in the current region settings
... map3d_1 = garray.array3d()
>>>
>>> # Write some data
... # Note: the 3D array has map[depth][row][column] order
... for z in range(map3d_1.shape[0]):
... for y in range(map3d_1.shape[1]):
... for x in range(map3d_1.shape[2]):
... map3d_1[z, y, x] = z + y + x
>>> # Lets have a look at the 3D array
... print(map3d_1)
[[[ 0. 1. 2. 3. 4. 5.]
[ 1. 2. 3. 4. 5. 6.]
[ 2. 3. 4. 5. 6. 7.]
[ 3. 4. 5. 6. 7. 8.]]
[[ 1. 2. 3. 4. 5. 6.]
[ 2. 3. 4. 5. 6. 7.]
[ 3. 4. 5. 6. 7. 8.]
[ 4. 5. 6. 7. 8. 9.]]
[[ 2. 3. 4. 5. 6. 7.]
[ 3. 4. 5. 6. 7. 8.]
[ 4. 5. 6. 7. 8. 9.]
[ 5. 6. 7. 8. 9. 10.]]]
>>> # This will write the numpy array as GRASS 3D raster map
... # with name map3d_1
... map3d_1.write(mapname="map3d_1", overwrite=True)
0
>>> # We create a new 3D array from 3D raster map3d_1 to modify it
... map3d_2 = garray.array3d(mapname="map3d_1")
>>> # Don't do map3d_2 = map3d_1 % 3
... # because: this will overwrite the internal temporary filename
... map3d_2 %= 3
>>> # Show the result
... print(map3d_2)
[[[0. 1. 2. 0. 1. 2.]
[1. 2. 0. 1. 2. 0.]
[2. 0. 1. 2. 0. 1.]
[0. 1. 2. 0. 1. 2.]]
[[1. 2. 0. 1. 2. 0.]
[2. 0. 1. 2. 0. 1.]
[0. 1. 2. 0. 1. 2.]
[1. 2. 0. 1. 2. 0.]]
[[2. 0. 1. 2. 0. 1.]
[0. 1. 2. 0. 1. 2.]
[1. 2. 0. 1. 2. 0.]
[2. 0. 1. 2. 0. 1.]]]
>>> # Write the result as new 3D raster map with name map3d_2
... map3d_2.write(mapname="map3d_2", overwrite=True)
0
(C) 2010-2021 by Glynn Clements and the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- class script.array.array(mapname=None, null=None, dtype=<class 'numpy.float64'>, env=None)[source]¶
Bases:
memmap
Define new numpy array
- Parameters:
cls
dtype – data type (default: numpy.double)
env – environment
script.core module¶
Core functions to be used in Python scripts.
- Usage:
from grass.script import core as grass grass.parser()
(C) 2008-2025 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- class script.core.Popen(args, **kwargs)[source]¶
Bases:
Popen
Create new Popen instance.
- class StdinWrapper(stdin, implied_text)[source]¶
Bases:
object
Decodes bytes into str if writing failed and text mode was automatically set.
Remove for version 9
- property stdin¶
- script.core.compare_key_value_text_files(filename_a, filename_b, sep=':', val_sep=',', precision=1e-06, proj=False, units=False)[source]¶
Compare two key-value text files
This method will print a warning in case keys that are present in the first file are not present in the second one. The comparison method tries to convert the values into their native format (float, int or string) to allow correct comparison.
An example key-value text file may have this content:
a: Hello b: 1.0 c: 1,2,3,4,5 d : hello,8,0.1
- Parameters:
filename_a (str) – name of the first key-value text file
filename_b (str) – name of the second key-value text file
sep (str) – character that separates the keys and values, default is “:”
val_sep (str) – character that separates the values of a single key, default is “,”
precision (double) – precision with which the floating point values are compared
proj (bool) – True if it has to check some information about projection system
units (bool) – True if it has to check some information about units
- Returns:
True if full or almost identical, False if different
- script.core.create_environment(gisdbase, location, mapset, env=None)[source]¶
Creates environment to be passed in run_command for example. Returns tuple with temporary file path and the environment. The user of this function is responsible for deleting the file.
- script.core.create_project(path, name=None, epsg=None, proj4=None, filename=None, wkt=None, datum=None, datum_trans=None, desc=None, overwrite=False)[source]¶
Create new project
- Parameters:
path (str) – path to GRASS database or project; if path to database, project name must be specified with name parameter
name (str) – project name to create
epsg – if given create new project based on EPSG code
proj4 – if given create new project based on Proj4 definition
filename (str) – if given create new project based on georeferenced file
wkt (str) – if given create new project based on WKT definition (can be path to PRJ file or WKT string)
datum – GRASS format datum code
datum_trans – datum transformation parameters (used for epsg and proj4)
desc – description of the project (creates MYNAME file)
overwrite (bool) – True to overwrite project if exists (WARNING: ALL DATA from existing project ARE DELETED!)
- Raises:
ScriptError – Raise
ScriptError
on error
- script.core.debug(msg, debug=1, env=None)[source]¶
Display a debugging message using
g.message -d
.The visibility of a debug message at runtime is controlled by setting the corresponding DEBUG level with
g.gisenv set="DEBUG=X"
(withX
set to the debug level specified in the function call).- Parameters:
msg (str) – debugging message to be displayed
debug (str) – debug level (0-5) with the following recommended levels: - Use 1 for messages generated once of few times, - 3 for messages generated for each raster row or vector line, - 5 for messages generated for each raster cell or vector point.
env – dictionary with system environment variables (
os.environ
by default)
- script.core.del_temp_region()[source]¶
Unsets WIND_OVERRIDE and removes any region named by it.
See also
The
g.remove
tool
- script.core.error(msg, env=None)[source]¶
Display an error message using
g.message -e
This function does not end the execution of the program. The right action after the error is up to the caller. For error handling using the standard mechanism use
fatal()
.- Parameters:
msg (str) – error message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.core.exec_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, env=None, **kwargs)[source]¶
Interface to os.execvpe(), but with the make_command() interface.
- Parameters:
prog (str) – GRASS module
flags (str) – flags to be used (given as a string)
overwrite (bool) – True to enable overwriting the output (
--o
)quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)env – dictionary with system environment variables (
os.environ
by default)kwargs (list) – module’s parameters
- script.core.fatal(msg, env=None)[source]¶
Display an error message using
g.message -e
, then abort or raiseRaises exception when module global
raise_on_error
is ‘True’, abort (callssys.exit()
) otherwise. Useset_raise_on_error()
to set the behavior.- Parameters:
msg (str) – error message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- Raises:
ScriptError – Raises exception when module global
raise_on_error
is ‘True’
- script.core.feed_command(*args, **kwargs)[source]¶
Passes all arguments to
start_command()
, but also adds “stdin = PIPE”. Returns thePopen
object.- Parameters:
args (list) – list of unnamed arguments (see
start_command()
for details)kwargs (list) – list of named arguments (see
start_command()
for details)
- Returns:
Popen object
- Return type:
- script.core.find_file(name, element='cell', mapset=None, env=None)[source]¶
Returns the output from running g.findfile as a dictionary.
Elements in g.findfile refer to mapset directories. However, in parts of the code, different element terms like rast, raster, or rast3d are used. For convenience the function translates such element types to respective mapset elements. Current translations are: “rast”: “cell”, “raster”: “cell”, “rast3d”: “grid3”, “raster3d”: “grid3”, “raster_3d”: “grid3”,
- Example:
>>> result = find_file("elevation", element="cell") >>> print(result["fullname"]) elevation@PERMANENT >>> print(result["file"]) /.../PERMANENT/cell/elevation >>> result = find_file("elevation", element="raster") >>> print(result["fullname"]) elevation@PERMANENT >>> print(result["file"]) /.../PERMANENT/cell/elevation
- Parameters:
- Returns:
parsed output of g.findfile
See also
The
g.findfile
tool
- script.core.find_program(pgm, *args, env: Mapping[str, str] = None)[source]¶
Attempt to run a program, with optional arguments.
You must call the program in a way that will return a successful exit code. For GRASS modules this means you need to pass it some valid CLI option, like “
--help
”. For other programs a common valid do-little option is usually “--version
”.- Example:
>>> find_program("r.sun", "--help") True >>> find_program("ls", "--version") True
- Parameters:
pgm (str) – program name
args – list of arguments
env – environment
- Returns:
False if the attempt failed due to a missing executable or non-zero return code
- Returns:
True otherwise
- script.core.get_capture_stderr()[source]¶
Return True if stderr is captured, False otherwise.
See also
- script.core.get_commands(*, env=None)[source]¶
Create list of available GRASS commands to use when parsing string from the command line
- Returns:
list of commands (set) and directory of scripts (collected by extension - MS Windows only)
>>> cmds = list(get_commands()[0]) >>> cmds.sort() >>> cmds[:5] ['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate', 'd.erase']
- script.core.get_raise_on_error()[source]¶
Return True if a
ScriptError
exception is raised instead of callingsys.exit(1)
in case a fatal error was invoked withfatal()
.
- script.core.get_real_command(cmd)[source]¶
Returns the real file command for a module (cmd)
For Python scripts on MS Windows it returns full path to the script and adds a ‘.py’ extension. For other cases it just returns a module (name). So, you can just use this function for all without further check.
>>> get_real_command("g.region") 'g.region'
- Parameters:
cmd – the command
- script.core.gisenv(env: Mapping[str, str] | None = None) KeyValue[str | None] [source]¶
Returns the output from running g.gisenv (with no arguments), as a dictionary.
- Example:
>>> env = gisenv() >>> print(env["GISDBASE"]) /opt/grass-data
- Parameters:
env – dictionary with system environment variables (
os.environ
by default)- Returns:
list of GRASS variables
- script.core.handle_errors(returncode, result, args, kwargs, handler=None, stderr=None, exception=None, env=None)[source]¶
Error handler for
run_command()
and similar functionsThe functions which are using this function to handle errors, can be typically called with an errors parameter. This function can handle one of the following values: raise, fatal, status, exit, and ignore. The value raise is a default. Alternatively, when this function is called explicitly, the parameter handler can be specified with the same values as errors.
If returncode is 0, result is returned, unless
errors="status"
is set.If kwargs dictionary contains key
errors
, the value is used to determine the return value and the behavior on error. The valueerrors="raise"
is a default in which case aCalledModuleError
exception is raised.For
errors="fatal"
, the function callsfatal()
which has its own rules on what happens next. In this case, env parameter should also be provided unless the caller code relies on a global session. Besides the env parameter, env can be also provided in kwargs.For
errors="status"
, the returncode will be returned. This is useful, e.g., for cases when the exception-based error handling mechanism is not desirable or the return code has some meaning not necessarily interpreted as an error by the caller.For
errors="exit"
,sys.exit()
is called with the returncode, so it behaves similarly to a Bash script withset -e
. No additional error message or exception is produced. This might be useful for a simple script where error message produced by the called module provides sufficient information about what happened to the end user.Finally, for
errors="ignore"
, the value of result will be passed in any case regardless of the returncode.If stderr is provided, it is passed to
CalledModuleError
to build an error message witherrors="raise"
. Witherrors="exit"
, it is printed tosys.stderr
.This function is intended to be used as an error handler or handler of potential errors in code which wraps calling of tools as subprocesses. Typically, this function is not called directly in user code or in a tool code unless the tools are handed directly, e.g., with
Popen
as opposed torun_command()
.- Raises:
If there is an error, and the
errors
parameter is not givenIf the
errors
parameter is given and it is notstatus
,ignore
,fatal
, norexit
.
- script.core.info(msg, env=None)[source]¶
Display an informational message using
g.message -i
- Parameters:
msg (str) – informational message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.core.legal_name(s)[source]¶
Checks if the string contains only allowed characters.
This is the Python implementation of
G_legal_filename()
function.Note
It is not clear when exactly use this function, but it might be useful anyway for checking map names and column names.
- script.core.list_grouped(type, pattern=None, check_search_path=True, exclude=None, flag='', env=None)[source]¶
List of elements grouped by mapsets.
Returns the output from running g.list, as a dictionary where the keys are mapset names and the values are lists of maps in that mapset.
- Example:
>>> list_grouped("vect", pattern="*roads*")["PERMANENT"] ['railroads', 'roadsmajor']
- Parameters:
type (str) – element type (raster, vector, raster_3d, region, …) or list of elements
pattern (str) – pattern string
check_search_path (str) – True to add mapsets for the search path with no found elements
exclude (str) – pattern string to exclude maps from the research
flag (str) – pattern type: ‘r’ (basic regexp), ‘e’ (extended regexp), or ‘’ (glob pattern)
env – environment
- Returns:
directory of mapsets/elements
See also
The
g.list
tool
- script.core.list_pairs(type, pattern=None, mapset=None, exclude=None, flag='', env=None)[source]¶
List of elements as pairs
Returns the output from running g.list, as a list of (name, mapset) pairs
- Parameters:
type (str) – element type (raster, vector, raster_3d, region, …)
pattern (str) – pattern string
mapset (str) – mapset name (if not given use search path)
exclude (str) – pattern string to exclude maps from the research
flag (str) – pattern type: ‘r’ (basic regexp), ‘e’ (extended regexp), or ‘’ (glob pattern)
env – environment
- Returns:
list of elements
See also
The
g.list
tool
- script.core.list_strings(type, pattern=None, mapset=None, exclude=None, flag='', env=None)[source]¶
List of elements as strings.
Returns the output from running g.list, as a list of qualified names.
- Parameters:
type (str) – element type (raster, vector, raster_3d, region, …)
pattern (str) – pattern string
mapset (str) – mapset name (if not given use search path)
exclude (str) – pattern string to exclude maps from the research
flag (str) – pattern type: ‘r’ (basic regexp), ‘e’ (extended regexp), or ‘’ (glob pattern)
env – environment
- Returns:
list of elements
See also
The
g.list
tool
- script.core.locn_is_latlong(env: Mapping[str, str] | None = None) bool [source]¶
Tests if location is lat/long. Value is obtained by checking the “g.region -pu” projection code.
- Returns:
True for a lat/long region, False otherwise
See also
The
g.region
tool
- script.core.make_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, errors=None, **options) list[str] [source]¶
Return a list of strings suitable for use as the args parameter to
Popen()
orcall()
.- Example:
>>> make_command("g.message", flags="w", message="this is a warning") ['g.message', '-w', 'message=this is a warning']
The single-character flags are supplied as a string, flags, containing individual flag characters. While an integer for a single flag and a leading dash are also accepted, the best practice is to provide the characters as a string without a leading dash.
- Parameters:
prog (str) – GRASS module
flags (str) – flags to be used (given as a string of flag characters)
overwrite (bool) – True to enable overwriting the output (
--o
)quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)options – module’s parameters
- Returns:
list of arguments
- script.core.mapsets(search_path=False, env=None)[source]¶
List available mapsets
- Parameters:
search_path (bool) – True to list mapsets only in search path
- Returns:
list of mapsets
See also
The
g.mapsets
tool
- script.core.message(msg, flag=None, env=None)[source]¶
Display a message using
g.message
- Parameters:
msg (str) – message to be displayed
flag (str) – flags (given as string)
env – dictionary with system environment variables (
os.environ
by default)
- script.core.parse_color(val: str, dflt: tuple[float, float, float] | None = None) tuple[float, float, float] | None [source]¶
Parses the string “val” as a GRASS colour, which can be either one of the named colours or an
R:G:B
tuple e.g.255:255:255
. Returns an (r,g,b) triple whose components are floating point values between 0 and 1.- Example:
>>> parse_color("red") (1.0, 0.0, 0.0) >>> parse_color("255:0:0") (1.0, 0.0, 0.0)
- Parameters:
val – color value
dflt – default color value
- Returns:
tuple RGB
- script.core.parse_command(*args, **kwargs)[source]¶
Passes all arguments to read_command, then parses the output by default with
parse_key_val()
.If the command has parameter
format
and is called withformat="json"
, the output will be parsed into a dictionary. Similarly, withformat="csv"
the output will be parsed into a list of lists (CSV rows).parse_command("v.db.select", ..., format="json")
Custom parsing function can be optionally given by
parse
parameter including its arguments, e.g.parse_command(..., parse=(gs.parse_key_val, {"sep": ":"}))
Parameter
delimiter
is deprecated.- Parameters:
args – list of unnamed arguments (see
start_command()
for details)kwargs –
list of named arguments (see
start_command()
for details)Deprecated since version 8.4.0: Parameter
delimiter
is deprecated. Use the command’sformat="json"
orformat="csv"
parameter instead
- Returns:
parsed module output
- script.core.parser() tuple[dict[str, str], dict[str, bool]] [source]¶
Interface to g.parser, intended to be run from the top-level, e.g.:
if __name__ == "__main__": options, flags = grass.parser() main()
Thereafter, the global variables “options” and “flags” will be dictionaries containing option/flag values, keyed by lower-case option/flag names. The values in “options” are strings, those in “flags” are Python booleans.
Overview table of parser standard options: https://grass.osgeo.org/grass-devel/manuals/parser_standard_options.html
- script.core.percent(i, n, s, env=None)[source]¶
Display a progress info message using
g.message -p
message(_("Percent complete...")) n = 100 for i in range(n): percent(i, n, 1) percent(1, 1, 1)
- Parameters:
i (int) – current item
n (int) – total number of items
s (int) – increment size
env – dictionary with system environment variables (
os.environ
by default)
- script.core.pipe_command(*args, **kwargs)[source]¶
Passes all arguments to
start_command()
, but also adds “stdout = PIPE”. Returns thePopen
object.>>> p = pipe_command("g.gisenv") >>> print(p) <....Popen object at 0x...> >>> print(p.communicate()[0]) GISDBASE='/opt/grass-data'; LOCATION_NAME='spearfish60'; MAPSET='glynn'; GUI='text'; MONITOR='x0';
- Parameters:
args (list) – list of unnamed arguments (see
start_command()
for details)kwargs (list) – list of named arguments (see
start_command()
for details)
- Returns:
Popen object
- Return type:
- script.core.popen_args_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, **kwargs)[source]¶
Split tool name and parameters from Popen parameters
Does the splitting based on known Popen parameter names, and then does the transformation from Python parameters to a list of command line arguments for
Popen
.
- script.core.read_command(*args, **kwargs)[source]¶
Passes all arguments to
pipe_command()
, then waits for the process to complete, returning its stdout (i.e. similar to shellbackticks
).The behavior on error can be changed using errors parameter which is passed to the
handle_errors()
function.- Parameters:
args (list) – list of unnamed arguments (see
start_command()
for details)kwargs (list) – list of named arguments (see
start_command()
for details)
- Returns:
stdout
- script.core.region(region3d=False, complete=False, env=None)[source]¶
Returns the output from running “g.region -gu”, as a dictionary.
- Example:
>>> curent_region = region() >>> # obtain n, s, e and w values >>> [curent_region[key] for key in "nsew"] [..., ..., ..., ...] >>> # obtain ns and ew resolutions >>> (curent_region["nsres"], curent_region["ewres"]) (..., ...)
- Parameters:
region3d (bool) – True to get 3D region
complete (bool)
env – dictionary with system environment variables (
os.environ
by default)
- Returns:
dictionary of region values
See also
The
g.region
tool
- script.core.region_env(region3d: bool = False, flags: str | None = None, env: Mapping[str, str] | None = None, **kwargs) str [source]¶
Returns region settings as a string which can used as GRASS_REGION environmental variable.
If no ‘kwargs’ are given then the current region is used. Note that this function doesn’t modify the current region!
See also
See also
use_temp_region()
for alternative method how to define temporary region used for raster-based computation.- Example:
os.environ["GRASS_REGION"] = grass.region_env(region="detail") grass.mapcalc("map=1", overwrite=True) os.environ.pop("GRASS_REGION")
- Parameters:
region3d – True to get 3D region
flags – for example ‘a’
env – dictionary with system environment variables (
os.environ
by default)kwargs – g.region’s parameters like ‘raster’, ‘vector’ or ‘region’
- Returns:
string with region values, or empty string on error
- script.core.run_command(*args, **kwargs)[source]¶
Execute a module synchronously
This function passes all arguments to
start_command()
, then waits for the process to complete. It is similar tosubprocess.check_call()
, but with themake_command()
interface. By default, an exception is raised in case of a non-zero return code by default.>>> run_command("g.region", raster="elevation")
See
start_command()
for details about parameters and usage.The behavior on error can be changed using errors parameter which is passed to the
handle_errors()
function.- Parameters:
args – unnamed arguments passed to
start_command()
kwargs – named arguments passed to
start_command()
errors (str) – passed to
handle_errors()
Changed in version 8.0: Before 8.0, the function was returning 0 when no error occurred for backward compatibility with code which was checking that value. Now the function returns None, unless
errors="status"
is specified.Changed in version 7.2: In 7.0.0, this function was returning the error code. However, it was rarely checked especially outside of the core code. Additionally,
read_command()
needed a mechanism to report errors as it was used more and more in context which required error handling, Thus, exceptions were introduced as a more expected default behavior for Python programmers. The change was backported to 7.0 series.- Raises:
CalledModuleError – When module returns non-zero return code.
- script.core.sanitize_mapset_environment(env)[source]¶
Remove environmental variables relevant only for a specific mapset. This should be called when a copy of environment is used with a different mapset.
- script.core.set_capture_stderr(capture=True)[source]¶
Enable capturing standard error output of modules and print it.
By default, standard error output (stderr) of child processes shows in the same place as output of the parent process. This may not always be the same place as
sys.stderr
is written. After calling this function, functions in thegrass.script
package will capture the stderr of child processes and pass it tosys.stderr
if there is an error.Note
This is advantageous for interactive shells such as the one in GUI and interactive notebooks such as Jupyter Notebook.
The capturing can be applied only in certain cases, for example in case of
run_command()
it is applied becauserun_command()
nor its callers do not handle the streams, howeverfeed_command()
cannot do capturing because its callers handle the streams.The previous state is returned. Passing
False
disables the capturing.Added in version 7.4.
See also
- script.core.set_raise_on_error(raise_exp=True)[source]¶
Define behavior on fatal error (
fatal()
called)- Parameters:
raise_exp (bool) – True to raise
ScriptError
instead of callingsys.exit(1)
infatal()
- Returns:
current status
- script.core.start_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, **kwargs) Popen [source]¶
Returns a
Popen
object with the command created bymake_command()
. Accepts any of the arguments whichPopen()
accepts apart from “args” and “shell”.>>> p = start_command("g.gisenv", stdout=subprocess.PIPE) >>> print(p) <...Popen object at 0x...> >>> print(p.communicate()[0]) GISDBASE='/opt/grass-data'; LOCATION_NAME='spearfish60'; MAPSET='glynn'; GUI='text'; MONITOR='x0';
If the module parameter is the same as Python keyword, add underscore at the end of the parameter. For example, use
lambda_=1.6
instead oflambda=1.6
.- Parameters:
prog (str) – GRASS module
flags (str) – flags to be used (given as a string)
overwrite (bool) – True to enable overwriting the output (
--o
)quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)kwargs – module’s parameters
- Returns:
Popen object
- Return type:
- script.core.tempdir(env=None)[source]¶
Returns the name of a temporary dir, created with g.tempfile.
See also
The
g.tempfile
tool, and thetempfile()
andtempname()
functions
- script.core.tempfile(create=True, env=None)[source]¶
Returns the name of a temporary file, created with g.tempfile.
- Parameters:
create (bool) – True to create a file
env – environment
- Returns:
path to a tmp file
See also
The
g.tempfile
tool, and thetempdir()
andtempname()
functions
- script.core.tempname(length: int, lowercase: bool = False) str [source]¶
Generate a GRASS and SQL compliant random name starting with
tmp_
followed by a random part of length “length”- Parameters:
length – length of the random part of the name to generate
lowercase – use only lowercase characters to generate name
- Returns:
String with a random name of length “length” starting with a letter
- Example:
>>> tempname(12) 'tmp_MxMa1kAS13s9'
See also
functions
append_uuid()
,append_random()
, theg.tempfile
tool, and thetempfile()
andtempdir()
functions
- script.core.use_temp_region()[source]¶
Copies the current region to a temporary region with “g.region save=”, then sets WIND_OVERRIDE to refer to that region. Installs an atexit handler to delete the temporary region upon termination.
See also
The
g.region
tool
- script.core.verbose(msg, env=None)[source]¶
Display a verbose message using
g.message -v
- Parameters:
msg (str) – verbose message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.core.verbosity()[source]¶
Return the verbosity level selected by GRASS_VERBOSE
Currently, there are 5 levels of verbosity: -1 nothing will be printed (also fatal errors and warnings will be discarded)
0 only errors and warnings are printed, triggered by “–q” or “–quiet” flag.
1 progress information (percent) and important messages will be printed
2 all messages will be printed
3 also verbose messages will be printed. Triggered by “
--v
” or “--verbose
” flag.
- script.core.version()[source]¶
Get GRASS version as dictionary
>>> print(version()) {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468', 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)', 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev', 'revision': '53670'}
- script.core.warning(msg, env=None)[source]¶
Display a warning message using
g.message -w
- Parameters:
msg (str) – warning message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.core.write_command(*args, **kwargs)[source]¶
Execute a module with standard input given by stdin parameter.
Passes all arguments to
feed_command()
, with the string specified by the stdin argument fed to the process’ standard input.>>> write_command( ... "v.in.ascii", ... input="-", ... stdin="%s|%s" % (635818.8, 221342.4), ... output="view_point", ... ) 0
See
start_command()
for details about parameters and usage.The behavior on error can be changed using errors parameter which is passed to the
handle_errors()
function.- Parameters:
args – unnamed arguments passed to
start_command()
kwargs – named arguments passed to
start_command()
- Returns:
0 with default parameters for backward compatibility only
- Raises:
CalledModuleError – When module returns non-zero return code
script.db module¶
Database related functions to be used in Python scripts.
- Usage:
from grass.script import db as grass grass.db_describe(table) ...
(C) 2008-2015 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- script.db.db_connection(force=False, env=None)[source]¶
Return the current database connection parameters (interface to
db.connect -g
).- Example:
>>> db_connection() {'group': '', 'schema': '', 'driver': 'sqlite', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'}
- Parameters:
force – True to set up default DB connection if not defined
env – environment
- Returns:
parsed output of db.connect
- script.db.db_describe(table, env=None, **args)[source]¶
Return the list of columns for a database table (interface to
db.describe -c
).- Example:
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_describe("myfirestations") {'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22} >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
- Returns:
parsed module output
- script.db.db_select(sql=None, filename=None, table=None, env=None, **args)[source]¶
Perform SQL select statement
Note
One of sql, filename, or table arguments must be provided.
- Example:
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_select(sql="SELECT cat,CITY FROM myfirestations WHERE cat < 4") (('1', 'Morrisville'), ('2', 'Morrisville'), ('3', 'Apex'))
Simplified usage (it performs
SELECT * FROM myfirestations
.)>>> db_select(table="myfirestations") (('1', '24', 'Morrisville #3', ... 'HS2A', '1.37')) >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
- script.db.db_table_exist(table, env=None, **args)[source]¶
Check if table exists.
If no driver or database are given, then default settings is used (check db_connection()).
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_table_exist("myfirestations") True >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
table (str) – table name
args
env – environment
- Returns:
True for success, False otherwise
- script.db.db_table_in_vector(table, mapset='.', env=None)[source]¶
Return the name of vector connected to the table. By default it check only in the current mapset, because the same table name could be used also in other mapset by other vector. It returns None if no vectors are connected to the table.
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_table_in_vector("myfirestations") ['myfirestations@user1'] >>> db_table_in_vector("mfirestations") >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
table (str) – name of table to query
env – environment
script.imagery module¶
Imagery related functions to be used in Python scripts.
- Usage:
import grass.script as gs gs.imagery.group_to_dict(imagery_group) ...
(C) 2024 by Stefan Blumentrath and the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- script.imagery.group_to_dict(imagery_group_name, subgroup=None, dict_keys='semantic_labels', dict_values='map_names', fill_semantic_label=True, env=None)[source]¶
Create a dictionary to represent an imagery group with metadata.
Depending on the dict_keys option, the returned dictionary uses either the names of the raster maps (“map_names”), their row indices in the group (“indices”) or their associated semantic_labels (“semantic_labels”) as keys. The default is to use semantic_labels. Note that map metadata of the maps in the group have to be read to get the semantic label, in addition to the group file. The same metadata is read when the “metadata” is requested as dict_values. Other supported dict_values are “map_names” (default), “semantic_labels”, or “indices”.
The function can also operate on the level of subgroups. In case a non-existing (or empty sub-group) is requested a warning is printed and an empty dictionary is returned (following the behavior of i.group).
- Example:
>>> run_command("g.copy", raster="lsat7_2000_10,lsat7_2000_10") >>> run_command("r.support", raster="lsat7_2000_10", semantic_label="L8_1") >>> run_command("g.copy", raster="lsat7_2000_20,lsat7_2000_20") >>> run_command("r.support", raster="lsat7_2000_20", semantic_label="L8_2") >>> run_command("g.copy", raster="lsat7_2000_30,lsat7_2000_30") >>> run_command("r.support", raster="lsat7_2000_30", semantic_label="L8_3") >>> run_command("i.group", group="L8_group", >>> input="lsat7_2000_10,lsat7_2000_20,lsat7_2000_30") >>> group_to_dict("L8_group") {"L8_1": "lsat7_2000_10", ... "L8_3": "lsat7_2000_30"} >>> run_command("g.remove", flags="f", type="group", name="L8_group") >>> run_command("g.remove", flags="f", type="raster", >>> name="lsat7_2000_10,lsat7_2000_20,lsat7_2000_30")
- Parameters:
imagery_group_name (str) – Name of the imagery group to process (or None)
subgroup (str) – Name of the imagery sub-group to process (or None)
dict_keys (str) – What to use as key for dictionary. It can be either “semantic_labels” (default), “map_names” or “indices”
dict_values (str) – What to use as values for dictionary. It can be either “map_names” (default), “semanic_labels”, “indices” or “metadata” (to return dictionaries with full map metadata)
fill_semantic_label (bool) – If maps in a group do not have a semantic label, their index in the group is used instead (default). Otherwise None / “none” is used.
env (dict) – Environment to use when parsing the imagery group
- Returns:
dictionary representing an imagery group with it’s maps and their semantic labels, row indices in the group, or metadata
- Return type:
script.raster module¶
Raster related functions to be used in Python scripts.
- Usage:
from grass.script import raster as grass grass.raster_history(map)
(C) 2008-2011 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- class script.raster.MaskManager(mask_name: str | None = None, env: dict[str, str] | None = None, remove: bool | None = None)[source]¶
Bases:
object
Context manager for setting and managing 2D raster mask.
The context manager makes it possible to have custom mask for the current process. In the following example, we set the mask using _r.mask_ which creates a new raster which represents the mask. The mask is deactivated at the end of the context by the context manager and the raster is removed.
>>> with gs.MaskManager(): ... gs.run_command("r.mask", raster="state_boundary") ... gs.parse_command("r.univar", map="elevation", format="json")
The _mask_name_ can be a name of an existing raster map and in that case, that raster map is used directly as is. If the raster map does not exist, the name will be used for the mask once it is created (with _r.mask_).
The following example uses an existing raster map directly as the mask. The mask is disabled at the end of the context, but the raster map is not removed.
>>> with gs.MaskManager(mask_name="state_boundary"): ... gs.parse_command("r.univar", map="elevation", format="json")
Example using explicit activate and deactivate:
>>> manager = gs.MaskManager() >>> manager.activate() >>> try: ... # Create mask with r.mask ... gs.run_command("r.mask", raster="state_boundary") ... gs.parse_command("r.univar", map="elevation", format="json") ... finally: ... manager.deactivate()
Note the difference between using the name of an existing raster map directly and using r.mask to create a new mask. Both zeros and NULL values are used to represent mask resulting in NULL cells, while r.mask by default sets the mask in the way that only NULL values in the original raster result in NULL cells.
If _mask_name_ is not provided, it generates a unique name using node (computer) name, PID (current process ID), and unique ID (UUID). In this case, the raster map representing the mask is removed if it exists at the end of the context. Optionally, the context manager can remove the raster map at the end of the context when _remove_ is set to
True
. The defaults for the removal of a mask raster are set to align with the two main use cases which is creating the mask within the context and using an existing raster as a mask.Name of the raster mask is available as the _mask_name_ attribute and can be used to directly create a mask (without the need to use r.mask). The following example uses the attribute to create a mask directly by name. This is equivalent to the basic case where a raster named
MASK
is created directly by the user in an interactive session.>>> with gs.MaskManager() as manager: ... gs.run_command( "r.mapcalc", expression=f"{manager.mask_name} = row() < col()" ) ... gs.run_command( "r.mapcalc", expression=f"masked_elevation = elevation" )
In the background, this class manages the
GRASS_MASK
environment variable. It modifies the current system environment or the one provided. It does not create a copy internally. However, the modified environment is available as the _env_ attribute for convenience and consistency with other managers which provide this attribute.The following code creates a copy of the global environment and lets the manager modify it. The copy is then available as the _env_ attribute.
>>> with gs.MaskManager(env=os.environ.copy()) as manager: ... gs.run_command( ... "r.mapcalc", ... expression=f"{manager.mask_name} = row() < col()", ... env=manager.env, ... ) ... gs.run_command( ... "r.mapcalc", expression=f"masked_elevation = elevation", env=manager.env ... )
Initializes the MaskManager.
- Parameters:
mask_name – Name of the raster mask. Generated if not provided.
env – Environment to use. Defaults to modifying os.environ.
remove – If True, the raster mask will be removed when the context exits. Defaults to True if the mask name is generated, and False if a mask name is provided.
- class script.raster.RegionManager(env: dict[str, str] | None = None, **kwargs)[source]¶
Bases:
object
Context manager for temporarily setting the computational region.
This context manager makes it possible to safely modify the computational region (for example via
g.region
) within awith
block. When the context exits, the original region settings are automatically restored. This is useful in scripts or functions that need to work with a specific region without permanently altering the user’s working environment.The new region can be defined by passing
g.region
parameters when initializing the context, or by callingg.region
directly within the context.The original region is saved at the beginning of the context and restored at the end.
Example with explicit region parameters:
>>> with gs.RegionManager(n=226000, s=222000, w=634000, e=638000): ... gs.parse_command("r.univar", map="elevation", format="json")
Example matching a raster map’s region:
>>> with gs.RegionManager(raster="elevation"): ... gs.run_command("r.slope.aspect", elevation="elevation", slope="slope")
Example using g.region:
>>> with gs.RegionManager(): ... gs.run_command("g.region", n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json")
Example using
set_region()
:>>> with gs.RegionManager() as manager: ... manager.set_region(n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json")
Example using explicit activate and deactivate:
>>> manager = gs.RegionManager(raster="elevation") >>> manager.activate() >>> try: ... gs.run_command("r.slope.aspect", elevation="elevation", slope="slope") ... finally: ... manager.deactivate()
If no environment is provided, the global environment is used. When running parallel processes in the same mapset that modify region settings, it is useful to use a copy of the global environment. The following code creates the copy of the global environment and lets the manager modify it. The copy is then available as the _env_ attribute.
>>> with gs.RegionManager(raster="elevation", env=os.environ.copy()) as manager: ... gs.run_command("r.univar", map="elevation", env=manager.env)
In the background, this class manages the
WIND_OVERRIDE
environment variable that holds the unique name of the saved region to use.Initializes the MaskManager.
- Parameters:
env – Environment to use. Defaults to modifying
os.environ
.kwargs – Keyword arguments passed to
g.region
- activate()[source]¶
Sets the
WIND_OVERRIDE
environment variable to the generated region name.- Returns:
Returns the
RegionManager
instance.
- class script.raster.RegionManagerEnv(env: dict[str, str] | None = None, **kwargs)[source]¶
Bases:
object
Context manager for temporarily setting the computational region.
See
RegionManager
. UnlikeRegionManager
, this class usesGRASS_REGION
instead ofWIND_OVERRIDE
. The advantage is no files are written to disk. The disadvantage is that simply callingg.region
within the context will not affect the temporary region, but the global one, which can be confusing.Example with explicit region parameters:
>>> with gs.RegionManagerEnv(n=226000, s=222000, w=634000, e=638000): ... gs.parse_command("r.univar", map="elevation", format="json")
Example with
set_region()
:>>> with gs.RegionManagerEnv() as manager: ... manager.set_region(n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json")
This is identical to:
>>> with gs.RegionManagerEnv() as manager: manager.env["GRASS_REGION"] = gs.region_env() ... gs.parse_command("r.univar", map="elevation", format="json")
Example using explicit activate and deactivate:
>>> manager = gs.RegionManagerEnv(raster="elevation") >>> manager.activate() >>> try: ... manager.set_region(n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json") ... finally: ... manager.deactivate()
Caution
To set region within the context, do not call
g.region
, useset_region()
instead.Initializes the MaskManager.
- Parameters:
env – Environment to use. Defaults to modifying
os.environ
.kwargs – Keyword arguments passed to
g.region
- activate()[source]¶
Sets the
GRASS_REGION
environment variable to the generated region name.- Returns:
Returns the
RegionManagerEnv
instance.
- script.raster.mapcalc(exp, quiet=False, superquiet=False, verbose=False, overwrite=False, seed=None, env=None, **kwargs)[source]¶
Interface to r.mapcalc.
- Parameters:
exp (str) – expression
quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)overwrite (bool) – True to enable overwriting the output (
--o
)seed – an integer used to seed the random-number generator for the rand() function, or ‘auto’ to generate a random seed
env (dict) – dictionary of environment variables for child process
kwargs
- script.raster.mapcalc_start(exp, quiet=False, superquiet=False, verbose=False, overwrite=False, seed=None, env=None, **kwargs)[source]¶
Interface to r.mapcalc, doesn’t wait for it to finish, returns Popen object.
>>> output = "newele" >>> input = "elevation" >>> expr1 = '"%s" = "%s" * 10' % (output, input) >>> expr2 = "..." # etc. >>> # launch the jobs: >>> p1 = mapcalc_start(expr1) >>> p2 = mapcalc_start(expr2) >>> # wait for them to finish: >>> p1.wait() 0 >>> p2.wait() 1 >>> run_command("g.remove", flags="f", type="raster", name=output)
- Parameters:
exp (str) – expression
quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)overwrite (bool) – True to enable overwriting the output (
--o
)seed – an integer used to seed the random-number generator for the rand() function, or ‘auto’ to generate a random seed
env (dict) – dictionary of environment variables for child process
kwargs
- Returns:
Popen object
- script.raster.raster_history(map, overwrite=False, env=None)[source]¶
Set the command history for a raster map to the command used to invoke the script (interface to
r.support
).- Parameters:
map (str) – map name
env – environment
- Returns:
True on success
- Returns:
False on failure
- script.raster.raster_info(map, env=None)[source]¶
Return information about a raster map (interface to
r.info -gre
).- Example:
>>> raster_info("elevation") {'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}
- Parameters:
map (str) – map name
env – environment
- Returns:
parsed raster info
script.raster3d module¶
Raster3d related functions to be used in Python scripts.
- Usage:
from grass.script import raster3d as grass grass.raster3d_info(map)
(C) 2008-2016 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- script.raster3d.mapcalc3d(exp, quiet=False, superquiet=False, verbose=False, overwrite=False, seed=None, env=None, **kwargs)[source]¶
Interface to r3.mapcalc.
- Parameters:
exp (str) – expression
quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)overwrite (bool) – True to enable overwriting the output (
--o
)seed – an integer used to seed the random-number generator for the
rand()
function, or ‘auto’ to generate a random seedenv (dict) – dictionary of environment variables for child process
kwargs
- script.raster3d.raster3d_info(map, env=None)[source]¶
Return information about a raster3d map (interface to
r3.info
).- Example:
>>> mapcalc3d("volume = row() + col() + depth()") >>> raster3d_info("volume") {'vertical_units': '"units"', 'tbres': 1.0, ... 'south': 185000.0} >>> run_command("g.remove", flags="f", type="raster_3d", name="volume") 0
- Parameters:
map (str) – map name
env – environment
- Returns:
parsed raster3d info
script.setup module¶
Setup, initialization, and clean-up functions
Functions can be used in Python scripts to setup a GRASS environment and session without using grassXY.
- Usage:
import os import sys import subprocess # define GRASS Database # add your path to grassdata (GRASS database) directory gisdb = "~/grassdata" # the following path is the default path on MS Windows # gisdb = "~/Documents/grassdata" # specify (existing) Location and Mapset location = "nc_spm_08" mapset = "user1" # path to the GRASS launch script # we assume that the GRASS start script is available and on PATH # query GRASS itself for its GISBASE # (with fixes for specific platforms) # needs to be edited by the user executable = "grass" if sys.platform.startswith("win"): # MS Windows executable = r"C:\OSGeo4W\bin\grass.bat" # uncomment when using standalone WinGRASS installer # executable = r'C:\Program Files (x86)\GRASS <version>\grass.bat' # this can be skipped if GRASS executable is added to PATH elif sys.platform == "darwin": # macOS executable = f"/Applications/GRASS-<version>.app/Contents/Resources/bin/grass" # query GRASS itself for its Python package path grass_cmd = [executable, "--config", "python_path"] process = subprocess.run(grass_cmd, check=True, text=True, stdout=subprocess.PIPE) # define GRASS-Python environment sys.path.append(process.stdout.strip()) # import (some) GRASS Python bindings import grass.script as gs # launch session session = gs.setup.init(gisdb, location, mapset) # example calls gs.message("Current GRASS 8 environment:") print(gs.gisenv()) gs.message("Available raster maps:") for rast in gs.list_strings(type="raster"): print(rast) gs.message("Available vector maps:") for vect in gs.list_strings(type="vector"): print(vect) # clean up at the end session.finish()
(C) 2010-2025 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
@author Martin Landa <landa.martin gmail.com> @author Vaclav Petras <wenzeslaus gmail.com> @author Markus Metz
- class script.setup.SessionHandle(*, env, active=True, locked=False)[source]¶
Bases:
object
Object used to manage GRASS sessions.
Do not create objects of this class directly. Use the init function to get a session object.
- Basic usage:
# ... setup sys.path before import as needed import grass.script as gs session = gs.setup.init("~/grassdata/nc_spm_08/user1") # ... use GRASS modules here # end the session session.finish()
Context manager usage:
# ... setup sys.path before import as needed import grass.script as gs with gs.setup.init("~/grassdata/nc_spm_08/user1"): # ... use GRASS modules here pass # session ends automatically here when outside of the "with" block
The example above is modifying the global, process environment (
os.environ
). If you don’t want to modify the global environment, use the _env_ parameter for the _init_ function to modify the provided environment instead. This environment is then available as an attribute of the session object. The attribute then needs to be passed to all calls of GRASS tools and functions that wrap them. Context manager usage with custom environment:# ... setup sys.path before import as needed import grass.script as gs with gs.setup.init( "~/grassdata/nc_spm_08/user1", env=os.environ.copy() ) as session: # ... use GRASS modules here with env parameter gs.run_command("g.region", flags="p", env=session.env) # session ends automatically here, global environment was never modified
- property active¶
True if session is active (not finished)
- property env¶
- script.setup.call(cmd, **kwargs)[source]¶
Wrapper for subprocess.call to deal with platform-specific issues
- script.setup.clean_default_db(*, modified_after=None, env=None, gis_env=None)[source]¶
Clean (vacuum) the default db if it is SQLite
When modified_after is set, database is cleaned only when it was modified since the modified_after time.
- script.setup.ensure_runtime_env(env=None)[source]¶
Ensure that GRASS runtime environment is set up.
If the environment is set up, does nothing. Otherwise, it modifies the environment to activate the runtime environment. It does not start a session connected to a project.
If env is not provided, uses the global environment (os.environ).
- script.setup.finish(*, env=None, start_time=None, unlock=False)[source]¶
Terminate the GRASS session and clean up
GRASS commands can no longer be used after this function has been called
- Basic usage:
import grass.script as gs gs.setup.finish()
The function is not completely symmetrical with
init()
because it only closes the mapset, but doesn’t undo the runtime environment setup.When start_time is set, it might be used to determine cleaning procedures. Currently, it is used to do SQLite database vacuum only when database was modified since the session started.
The function does not check whether the mapset is locked or not, but unlock can be provided to unlock the mapset.
- script.setup.get_install_path(path=None)[source]¶
Get path to GRASS installation usable for setup of environmental variables.
The function tries to determine path tp GRASS installation so that the returned path can be used for setup of environmental variable for GRASS runtime. If the search fails, None is returned.
By default, the resulting path is derived relatively from the location of the Python package (specifically this module) in the file system. This derived path is returned only if it has subdirectories called
bin
andlib
. If the parameter or certain environmental variables are set, the following attempts are made to find the path.If path is provided and it is an existing executable, the executable is queried for the path. Otherwise, provided path is returned as is.
If path is not provided, the GISBASE environmental variable is used as the path if it exists. If GRASSBIN environmental variable exists and it is an existing executable, the executable is queried for the path.
If path is not provided and no relevant environmental variables are set, the default relative path search is performed. If that fails and executable called
grass
exists, it is queried for the path. None is returned if all the attempts failed.If an existing executable is called as a subprocess is called during the search and it fails, the CalledProcessError exception is propagated from the subprocess call.
- script.setup.init(path, location=None, mapset=None, *, grass_path=None, env=None, lock=False, timeout=0, force_unlock=False)[source]¶
Initialize system variables to run GRASS modules
This function is for running GRASS without starting it with the standard main executable grass. No GRASS modules shall be called before call of this function but any module or user script can be called afterwards because a GRASS session has been set up. GRASS Python libraries are usable as well in general but the ones using C libraries through
ctypes
are not (which is caused by library path not being updated for the current process which is a common operating system limitation).When the path or specified mapset does not exist, ValueError is raised.
The
get_install_path()
function is used to determine where the rest of GRASS files is installed. The grass_path parameter is passed to it if provided. If the path cannot be determined, ValueError is raised. Exceptions from the underlying function are propagated.To create a GRASS session a session file (aka gisrc file) is created. The session object returned by this function will take care of deleting it as long as the object is used as a context manager or the finish method of the object is called explicitly. Using methods of the session object is preferred over calling the function
finish()
.- Basic usage:
# ... setup GISBASE and sys.path before import import grass.script as gs session = gs.setup.init( "~/grassdata/nc_spm_08/user1", grass_path="/usr/lib/grass", ) # ... use GRASS modules here # end the session session.finish()
The returned object is a context manager, so the
with
statement can be used to ensure that the session is finished (closed) at the end:# ... setup sys.path before import import grass.script as gs with gs.setup.init("~/grassdata/nc_spm_08/user1"): # ... use GRASS modules here pass
A mapset can be locked which will prevent other session from locking it. A timeout can be specified to allow concurrent processes to wait for the lock to be released:
with gs.setup.init("~/grassdata/nc_spm_08/user1", lock=True, timeout=30): # ... use GRASS tools here pass
- Parameters:
path – path to GRASS database
location – location name
mapset – mapset within given location (default: ‘PERMANENT’)
grass_path – path to GRASS installation or executable
- Returns:
reference to a session handle object which is a context manager
- script.setup.runtime_env_is_active(env=None)[source]¶
Check that GRASS runtime environment is set up.
On a best-effort basis, it determines whether the GRASS runtime environment is set up. If so, it returns True; otherwise, it returns False.
If env is not provided, uses the global environment (os.environ).
- script.setup.setup_runtime_env(gisbase=None, *, env=None)[source]¶
Setup the runtime environment.
Modifies environment so that GRASS modules can run. It does not setup a session, but only the system environment to execute commands.
Modifies the environment provided with _env_. If _env_ is not provided, modifies the global environment (os.environ). Pass a copy of the environment if you don’t want the source environment modified.
If _gisbase_ is not provided, a heuristic is used to find the path to GRASS installation (see the
get_install_path()
function for details).
script.task module¶
Get interface description of GRASS commands
Based on gui/wxpython/gui_modules/menuform.py
Usage:
from grass.script import task as gtask
gtask.command_info("r.info")
(C) 2011 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- script.task.cmdlist_to_tuple(cmd)[source]¶
Convert command list to tuple for run_command() and others
- Parameters:
cmd (list) – GRASS command to be converted
- Returns:
command as tuple
- script.task.cmdstring_to_tuple(cmd)[source]¶
Convert command string to tuple for run_command() and others
- Parameters:
cmd (str) – command to be converted
- Returns:
command as tuple
- script.task.cmdtuple_to_list(cmd)[source]¶
Convert command tuple to list.
- Parameters:
cmd (tuple) – GRASS command to be converted
- Returns:
command in list
- script.task.command_info(cmd)[source]¶
Returns meta information for any GRASS command as dictionary with entries for description, keywords, usage, flags, and parameters, e.g.
>>> command_info("g.tempfile") {'keywords': ['general', 'support'], 'params': [{'gisprompt': False, 'multiple': False, 'name': 'pid', 'guidependency': '', 'default': '', 'age': None, 'required': True, 'value': '', 'label': '', 'guisection': '', 'key_desc': [], 'values': [], 'values_desc': [], 'prompt': None, 'hidden': False, 'element': None, 'type': 'integer', 'description': 'Process id to use when naming the tempfile'}], 'flags': [{'description': "Dry run - don't create a file, just prints it's file name", 'value': False, 'label': '', 'guisection': '', 'suppress_required': False, 'hidden': False, 'name': 'd'}, {'description': 'Print usage summary', 'value': False, 'label': '', 'guisection': '', 'suppress_required': False, 'hidden': False, 'name': 'help'}, {'description': 'Verbose module output', 'value': False, 'label': '', 'guisection': '', 'suppress_required': False, 'hidden': False, 'name': 'verbose'}, {'description': 'Quiet module output', 'value': False, 'label': '', 'guisection': '', 'suppress_required': False, 'hidden': False, 'name': 'quiet'}], 'description': "Creates a temporary file and prints it's file name.", 'usage': 'g.tempfile pid=integer [--help] [--verbose] [--quiet]'}
>>> command_info("v.buffer") ['vector', 'geometry', 'buffer']
- Parameters:
cmd (str) – the command to query
- script.task.get_interface_description(cmd)[source]¶
Returns the XML description for the GRASS cmd (force text encoding to “utf-8”).
The DTD must be located in $GISBASE/gui/xml/grass-interface.dtd, otherwise the parser will not succeed.
- Parameters:
cmd – command (name of GRASS module)
- Raises:
ScriptError – When unable to fetch the interface description for a command.
- class script.task.grassTask(path=None, blackList=None)[source]¶
Bases:
object
This class holds the structures needed for filling by the parser
Parameter blackList is a dictionary with fixed structure, eg.
blackList = { "items": {"d.legend": {"flags": ["m"], "params": []}}, "enabled": True, }
- Parameters:
path (str) – full path
blackList – hide some options in the GUI (dictionary)
- get_cmd(ignoreErrors=False, ignoreRequired=False, ignoreDefault=True)[source]¶
Produce an array of command name and arguments for feeding into some execve-like command processor.
- Parameters:
- Raises:
ValueError – When
ignoreErrors=False
and there are errors
- get_cmd_error() list[str] [source]¶
Get error string produced by get_cmd(ignoreErrors = False)
- Returns:
list of errors
- get_description(full=True)[source]¶
Get module’s description
- Parameters:
full (bool) – True for label + desc
- get_flag(aFlag)[source]¶
Find and return a flag by name
Raises ValueError when the flag is not found.
- Parameters:
aFlag (str) – name of the flag
- Raises:
ValueError – When the flag is not found.
- get_list_params(element='name')[source]¶
Get list of parameters
- Parameters:
element (str) – element name
- script.task.parse_interface(name, parser=<class 'script.task.processTask'>, blackList=None)[source]¶
Parse interface of given GRASS module
The name is either GRASS module name (of a module on path) or a full or relative path to an executable.
- Parameters:
name (str) – name of GRASS module to be parsed
parser
blackList
- Raises:
ScriptError – When the interface description of a module cannot be parsed.
- class script.task.processTask(tree, task=None, blackList=None)[source]¶
Bases:
object
A ElementTree handler for the –interface-description output, as defined in grass-interface.dtd. Extend or modify this and the DTD if the XML output of GRASS’ parser is extended or modified.
- Parameters:
tree – root tree node
task – grassTask instance or None
blackList – list of flags/params to hide
- Returns:
grassTask instance
script.utils module¶
Useful functions to be used in Python scripts.
Usage:
from grass.script import utils as gutils
(C) 2014-2016 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- class script.utils.KeyValue[source]¶
-
A general-purpose key-value store.
KeyValue is a subclass of dict, but also allows entries to be read and written using attribute syntax.
- Example:
>>> reg = KeyValue() >>> reg["north"] = 489 >>> reg.north 489 >>> reg.south = 205 >>> reg["south"] 205
The keys of KeyValue are strings. To use other key types, use other mapping types. To use the attribute syntax, the keys must be valid Python attribute names.
- script.utils.append_node_pid(name)[source]¶
Add node name and PID to a name (string)
For the result to be unique, the name needs to be unique within a process. Given that, the result will be unique enough for use in temporary maps and other elements on single machine or an HPC cluster.
The returned string is a name usable for vectors, tables, and columns (vector legal name) as long as provided argument name is.
>>> append_node_pid("tmp_raster_1")
Note
Before you use this function for creating temporary files (i.e., normal files on disk, not maps and other mapset elements), see functions designed for it in the GRASS or standard Python library. These take care of collisions already on different levels.
- script.utils.append_random(name, suffix_length=None, total_length=None)[source]¶
Add a random part to of a specified length to a name (string)
>>> append_random("tmp", 8) >>> append_random("tmp", total_length=16)
Note
Note that this will be influenced by the random seed set for the Python random package.
Note
See the note about creating temporary files in the
append_node_pid()
description.
- script.utils.append_uuid(name)[source]¶
Add UUID4 to a name (string)
To generate a name of an temporary mapset element which is unique in a system, use
append_node_pid()
in a combination with a name unique within your process.To avoid collisions, never shorten the name obtained from this function. A shortened UUID does not have the collision guarantees the full UUID has.
For a random name of a given shorter size, see
append_random()
.>>> append_uuid("tmp")
Note
See the note about creating temporary files in the
append_node_pid()
description.
- script.utils.basename(path: StrPath, ext: str | None = None) str [source]¶
Remove leading directory components and an optional extension from the specified path
- script.utils.clock()[source]¶
Return time counter to measure performance for chunks of code. Should be used only as difference between the calls.
- script.utils.decode(bytes_: AnyStr, encoding: str | None = None) str [source]¶
Decode bytes with default locale and return (unicode) string
No-op if parameter is not bytes (assumed unicode string).
- Parameters:
bytes_ – the bytes to decode
encoding – encoding to be used, default value is None
Example¶
>>> decode(b"Südtirol") u'Südtirol' >>> decode("Südtirol") u'Südtirol' >>> decode(1234) u'1234'
- script.utils.diff_files(filename_a: FileDescriptorOrPath, filename_b: FileDescriptorOrPath) list[str] [source]¶
Diffs two text files and returns difference.
- script.utils.encode(string: AnyStr, encoding: str | None = None) bytes [source]¶
Encode string with default locale and return bytes with that encoding
No-op if parameter is bytes (assumed already encoded). This ensures garbage in, garbage out.
- Parameters:
string – the string to encode
encoding – encoding to be used, default value is None
Example¶
>>> encode(b"Südtirol") b'Südtirol' >>> decode("Südtirol") b'Südtirol' >>> decode(1234) b'1234'
- script.utils.float_or_dms(s) float [source]¶
Convert DMS to float.
>>> round(float_or_dms("26:45:30"), 5) 26.75833 >>> round(float_or_dms("26:0:0.1"), 5) 26.00003
- Parameters:
s – DMS value
- Returns:
float value
- script.utils.get_lib_path(modname, libname=None)[source]¶
Return the path of the libname contained in the module.
- script.utils.get_num_suffix(number, max_number)[source]¶
Returns formatted number with number of padding zeros depending on maximum number, used for creating suffix for data series. Does not include the suffix separator.
- Parameters:
number – number to be formatted as map suffix
max_number – maximum number of the series to get number of digits
>>> get_num_suffix(10, 1000) '0010' >>> get_num_suffix(10, 10) '10'
- script.utils.legalize_vector_name(name, fallback_prefix: str | None = 'x') str [source]¶
Make name usable for vectors, tables, and columns
The returned string is a name usable for vectors, tables, and columns, i.e., it is a vector legal name which is a string containing only lowercase and uppercase ASCII letters, digits, and underscores.
Invalid characters are replaced by underscores. If the name starts with an invalid character, the name is prefixed with fallback_prefix. This increases the length of the resulting name by the length of the prefix.
The fallback_prefix can be empty which is useful when the name is later used as a suffix for some other valid name.
ValueError is raised when provided name is empty or fallback_prefix does not start with a valid character.
- script.utils.natural_sort(items)[source]¶
Returns sorted list using natural sort (deprecated, use naturally_sorted)
- script.utils.parse_key_val(s: AnyStr, sep: str = '=', dflt: T | None = None, val_type: None = None, vsep: str | None = None) KeyValue[str | T | None] [source]¶
- script.utils.parse_key_val(s: AnyStr, sep: str = '=', dflt: T | None = None, val_type: Callable[[str], T] = None, vsep: str | None = None) KeyValue[T | None]
- script.utils.parse_key_val(s: AnyStr, sep: str = '=', dflt: T | None = None, val_type: Callable[[str], T] | None = None, vsep: str | None = None) KeyValue[str | T] | KeyValue[T | None] | KeyValue[T] | KeyValue[str | T | None]
Parse a string into a dictionary, where entries are separated by newlines and the key and value are separated by
sep
(default:=
)>>> parse_key_val("min=20\nmax=50") == {"min": "20", "max": "50"} True >>> parse_key_val("min=20\nmax=50", val_type=float) == {"min": 20, "max": 50} True
- Parameters:
s – string to be parsed
sep – key/value separator
dflt – default value to be used
val_type – value type (None for no cast)
vsep – vertical separator (default is Python ‘universal newlines’ approach)
- Returns:
parsed input (dictionary of keys/values)
- script.utils.separator(sep: str) str [source]¶
Returns separator from G_OPT_F_SEP appropriately converted to character.
>>> separator("pipe") '|' >>> separator("comma") ','
If the string does not match any of the separator keywords, it is returned as is:
>>> separator(", ") ', '
- Parameters:
separator (str) – character or separator keyword
- Returns:
separator character
- script.utils.set_path(modulename, dirname=None, path='.')[source]¶
Set sys.path looking in the local directory GRASS directories.
- Parameters:
modulename – string with the name of the GRASS module
dirname – string with the directory name containing the python libraries, default None
path – string with the path to reach the dirname locally.
Example¶
“set_path” example working locally with the source code of a module (r.green) calling the function with all the parameters. Below it is reported the directory structure on the r.green module.
grass_prompt> pwd ~/Download/r.green/r.green.hydro/r.green.hydro.financial grass_prompt> tree ../../../r.green ../../../r.green |-- ... |-- libgreen | |-- pyfile1.py | +-- pyfile2.py +-- r.green.hydro |-- Makefile |-- libhydro | |-- pyfile1.py | +-- pyfile2.py |-- r.green.hydro.* +-- r.green.hydro.financial |-- Makefile |-- ... +-- r.green.hydro.financial.py 21 directories, 125 files
in the source code the function is called with the following parameters:
set_path("r.green", "libhydro", "..") set_path("r.green", "libgreen", os.path.join("..", ".."))
when we are executing the module: r.green.hydro.financial locally from the command line:
grass_prompt> python r.green.hydro.financial.py --ui
In this way we are executing the local code even if the module was already installed as grass-addons and it is available in GRASS standards path.
The function is checking if the dirname is provided and if the directory exists and it is available using the path provided as third parameter, if yes add the path to sys.path to be importable, otherwise it will check on GRASS standard paths.
- script.utils.split(s)[source]¶
Same shlex.split() func on all OS platforms
We don’t use parameter posix=True on the OS MS Windows due to incorrectly splitting command line parameters:
e.g. d.vect where=”cat < 10”
is split incorrectly as follows:
‘where=”cat’, ‘<’, ‘10”’
Should be:
‘where=cat < 10’
- Parameters:
s (str) – cmd string
return list: cmd list
- script.utils.text_to_string(text: AnyStr, encoding: str | None = None) str [source]¶
Convert text to str. Useful when passing text into environments, in Python 2 it needs to be bytes on Windows, in Python 3 in needs unicode.
- Parameters:
text – The text to convert to string
encoding – The encoding to be used to decode the text that will be converted
- Returns:
A (unicode) string
script.vector module¶
Vector related functions to be used in Python scripts.
Usage:
from grass.script import vector as grass
grass.vector_db(map)
(C) 2008-2010 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details.
- script.vector.vector_columns(map, layer=None, getDict=True, env=None, **kwargs)[source]¶
Return a dictionary (or a list) of the columns for the database table connected to a vector map (interface to
v.info -c
).>>> vector_columns("geology", getDict=True) {'PERIMETER': {'index': 2, 'type': 'DOUBLE PRECISION'}, 'GEOL250_': {'index': 3, 'type': 'INTEGER'}, 'SHAPE_area': {'index': 6, 'type': 'DOUBLE PRECISION'}, 'onemap_pro': {'index': 1, 'type': 'DOUBLE PRECISION'}, 'SHAPE_len': {'index': 7, 'type': 'DOUBLE PRECISION'}, 'cat': {'index': 0, 'type': 'INTEGER'}, 'GEOL250_ID': {'index': 4, 'type': 'INTEGER'}, 'GEO_NAME': {'index': 5, 'type': 'CHARACTER'}}
>>> vector_columns("geology", getDict=False) ['cat', 'onemap_pro', 'PERIMETER', 'GEOL250_', 'GEOL250_ID', 'GEO_NAME', 'SHAPE_area', 'SHAPE_len']
- script.vector.vector_db(map, env=None, **kwargs)[source]¶
Return the database connection details for a vector map (interface to
v.db.connect -g
).- Example:
>>> vector_db("geology") {1: {'layer': 1, ... 'table': 'geology'}}
- Parameters:
map (str) – vector map
kwargs – other v.db.connect’s arguments
env – environment
- Returns:
dictionary
- script.vector.vector_db_select(map, layer=1, env=None, **kwargs)[source]¶
Get attribute data of selected vector map layer.
Function returns list of columns and dictionary of values ordered by key column value.
- Example:
>>> print(vector_db_select("geology")["columns"]) ['cat', 'onemap_pro', 'PERIMETER', 'GEOL250_', 'GEOL250_ID', 'GEO_NAME', 'SHAPE_area', 'SHAPE_len'] >>> print(vector_db_select("geology")["values"][3]) ['3', '579286.875', '3335.55835', '4', '3', 'Zml', '579286.829631', '3335.557182'] >>> print(vector_db_select("geology", columns="GEO_NAME")["values"][3]) ['Zml']
- Parameters:
- Returns:
dictionary (‘columns’ and ‘values’)
- script.vector.vector_history(map, replace=False, env=None)[source]¶
Set the command history for a vector map to the command used to invoke the script (interface to
v.support
).
- script.vector.vector_info(map, layer=1, env=None)[source]¶
Return information about a vector map (interface to
v.info
).
- script.vector.vector_info_topo(map, layer=1, env=None)[source]¶
Return information about a vector map (interface to
v.info -t
).
- script.vector.vector_layer_db(map, layer, env=None)[source]¶
Return the database connection details for a vector map layer. If db connection for given layer is not defined, fatal() is called.
- Parameters:
map (str) – map name
layer – layer number
env – environment
- Returns:
parsed output
- script.vector.vector_what(map, coord, distance=0.0, ttype=None, encoding=None, skip_attributes=False, layer=None, multiple=False, env=None)[source]¶
Query vector map at given locations
To query one vector map at one location
print grass.vector_what(map='archsites', coord=(595743, 4925281), distance=250) [{'Category': 8, 'Map': 'archsites', 'Layer': 1, 'Key_column': 'cat', 'Database': '/home/martin/grassdata/spearfish60/PERMANENT/dbf/', 'Mapset': 'PERMANENT', 'Driver': 'dbf', 'Attributes': {'str1': 'No_Name', 'cat': '8'}, 'Table': 'archsites', 'Type': 'Point', 'Id': 8}]
To query one vector map with multiple layers (no additional parameters required)
for q in grass.vector_what(map='some_map', distance=100.0, coord=(596532.357143,4920486.21429)): print q['Map'], q['Layer'], q['Attributes'] new_bug_sites 1 {'str1': 'Beetle_site', 'GRASSRGB': '', 'cat': '80'} new_bug_sites 2 {'cat': '80'}
To query more vector maps at one location
for q in grass.vector_what(map=('archsites', 'roads'), coord=(595743, 4925281), distance=250): print q['Map'], q['Attributes'] archsites {'str1': 'No_Name', 'cat': '8'} roads {'label': 'interstate', 'cat': '1'}
To query one vector map at more locations
for q in grass.vector_what(map='archsites', distance=250, coord=[(595743, 4925281), (597950, 4918898)]): print q['Map'], q['Attributes'] archsites {'str1': 'No_Name', 'cat': '8'} archsites {'str1': 'Bob_Miller', 'cat': '22'}
- Parameters:
map – vector map(s) to query given as string or list/tuple
coord – coordinates of query given as tuple (easting, northing) or list of tuples
distance – query threshold distance (in map units)
ttype – list of topology types (default of v.what are point, line, area, face)
encoding – attributes encoding
skip_attributes – True to skip querying attributes
layer – layer number or list of layers (one for each vector), if None, all layers (-1) are used
multiple – find multiple features within threshold distance
env –
environment
Deprecated since version 8.5.0: Parameter
encoding
is deprecated.
- Returns:
parsed list
Module contents¶
Python interface to launch GRASS modules in scripts
- class script.KeyValue[source]¶
-
A general-purpose key-value store.
KeyValue is a subclass of dict, but also allows entries to be read and written using attribute syntax.
- Example:
>>> reg = KeyValue() >>> reg["north"] = 489 >>> reg.north 489 >>> reg.south = 205 >>> reg["south"] 205
The keys of KeyValue are strings. To use other key types, use other mapping types. To use the attribute syntax, the keys must be valid Python attribute names.
- class script.MaskManager(mask_name: str | None = None, env: dict[str, str] | None = None, remove: bool | None = None)[source]¶
Bases:
object
Context manager for setting and managing 2D raster mask.
The context manager makes it possible to have custom mask for the current process. In the following example, we set the mask using _r.mask_ which creates a new raster which represents the mask. The mask is deactivated at the end of the context by the context manager and the raster is removed.
>>> with gs.MaskManager(): ... gs.run_command("r.mask", raster="state_boundary") ... gs.parse_command("r.univar", map="elevation", format="json")
The _mask_name_ can be a name of an existing raster map and in that case, that raster map is used directly as is. If the raster map does not exist, the name will be used for the mask once it is created (with _r.mask_).
The following example uses an existing raster map directly as the mask. The mask is disabled at the end of the context, but the raster map is not removed.
>>> with gs.MaskManager(mask_name="state_boundary"): ... gs.parse_command("r.univar", map="elevation", format="json")
Example using explicit activate and deactivate:
>>> manager = gs.MaskManager() >>> manager.activate() >>> try: ... # Create mask with r.mask ... gs.run_command("r.mask", raster="state_boundary") ... gs.parse_command("r.univar", map="elevation", format="json") ... finally: ... manager.deactivate()
Note the difference between using the name of an existing raster map directly and using r.mask to create a new mask. Both zeros and NULL values are used to represent mask resulting in NULL cells, while r.mask by default sets the mask in the way that only NULL values in the original raster result in NULL cells.
If _mask_name_ is not provided, it generates a unique name using node (computer) name, PID (current process ID), and unique ID (UUID). In this case, the raster map representing the mask is removed if it exists at the end of the context. Optionally, the context manager can remove the raster map at the end of the context when _remove_ is set to
True
. The defaults for the removal of a mask raster are set to align with the two main use cases which is creating the mask within the context and using an existing raster as a mask.Name of the raster mask is available as the _mask_name_ attribute and can be used to directly create a mask (without the need to use r.mask). The following example uses the attribute to create a mask directly by name. This is equivalent to the basic case where a raster named
MASK
is created directly by the user in an interactive session.>>> with gs.MaskManager() as manager: ... gs.run_command( "r.mapcalc", expression=f"{manager.mask_name} = row() < col()" ) ... gs.run_command( "r.mapcalc", expression=f"masked_elevation = elevation" )
In the background, this class manages the
GRASS_MASK
environment variable. It modifies the current system environment or the one provided. It does not create a copy internally. However, the modified environment is available as the _env_ attribute for convenience and consistency with other managers which provide this attribute.The following code creates a copy of the global environment and lets the manager modify it. The copy is then available as the _env_ attribute.
>>> with gs.MaskManager(env=os.environ.copy()) as manager: ... gs.run_command( ... "r.mapcalc", ... expression=f"{manager.mask_name} = row() < col()", ... env=manager.env, ... ) ... gs.run_command( ... "r.mapcalc", expression=f"masked_elevation = elevation", env=manager.env ... )
Initializes the MaskManager.
- Parameters:
mask_name – Name of the raster mask. Generated if not provided.
env – Environment to use. Defaults to modifying os.environ.
remove – If True, the raster mask will be removed when the context exits. Defaults to True if the mask name is generated, and False if a mask name is provided.
- class script.Popen(args, **kwargs)[source]¶
Bases:
Popen
Create new Popen instance.
- class StdinWrapper(stdin, implied_text)[source]¶
Bases:
object
Decodes bytes into str if writing failed and text mode was automatically set.
Remove for version 9
- property stdin¶
- class script.RegionManager(env: dict[str, str] | None = None, **kwargs)[source]¶
Bases:
object
Context manager for temporarily setting the computational region.
This context manager makes it possible to safely modify the computational region (for example via
g.region
) within awith
block. When the context exits, the original region settings are automatically restored. This is useful in scripts or functions that need to work with a specific region without permanently altering the user’s working environment.The new region can be defined by passing
g.region
parameters when initializing the context, or by callingg.region
directly within the context.The original region is saved at the beginning of the context and restored at the end.
Example with explicit region parameters:
>>> with gs.RegionManager(n=226000, s=222000, w=634000, e=638000): ... gs.parse_command("r.univar", map="elevation", format="json")
Example matching a raster map’s region:
>>> with gs.RegionManager(raster="elevation"): ... gs.run_command("r.slope.aspect", elevation="elevation", slope="slope")
Example using g.region:
>>> with gs.RegionManager(): ... gs.run_command("g.region", n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json")
Example using
set_region()
:>>> with gs.RegionManager() as manager: ... manager.set_region(n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json")
Example using explicit activate and deactivate:
>>> manager = gs.RegionManager(raster="elevation") >>> manager.activate() >>> try: ... gs.run_command("r.slope.aspect", elevation="elevation", slope="slope") ... finally: ... manager.deactivate()
If no environment is provided, the global environment is used. When running parallel processes in the same mapset that modify region settings, it is useful to use a copy of the global environment. The following code creates the copy of the global environment and lets the manager modify it. The copy is then available as the _env_ attribute.
>>> with gs.RegionManager(raster="elevation", env=os.environ.copy()) as manager: ... gs.run_command("r.univar", map="elevation", env=manager.env)
In the background, this class manages the
WIND_OVERRIDE
environment variable that holds the unique name of the saved region to use.Initializes the MaskManager.
- Parameters:
env – Environment to use. Defaults to modifying
os.environ
.kwargs – Keyword arguments passed to
g.region
- activate()[source]¶
Sets the
WIND_OVERRIDE
environment variable to the generated region name.- Returns:
Returns the
RegionManager
instance.
- class script.RegionManagerEnv(env: dict[str, str] | None = None, **kwargs)[source]¶
Bases:
object
Context manager for temporarily setting the computational region.
See
RegionManager
. UnlikeRegionManager
, this class usesGRASS_REGION
instead ofWIND_OVERRIDE
. The advantage is no files are written to disk. The disadvantage is that simply callingg.region
within the context will not affect the temporary region, but the global one, which can be confusing.Example with explicit region parameters:
>>> with gs.RegionManagerEnv(n=226000, s=222000, w=634000, e=638000): ... gs.parse_command("r.univar", map="elevation", format="json")
Example with
set_region()
:>>> with gs.RegionManagerEnv() as manager: ... manager.set_region(n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json")
This is identical to:
>>> with gs.RegionManagerEnv() as manager: manager.env["GRASS_REGION"] = gs.region_env() ... gs.parse_command("r.univar", map="elevation", format="json")
Example using explicit activate and deactivate:
>>> manager = gs.RegionManagerEnv(raster="elevation") >>> manager.activate() >>> try: ... manager.set_region(n=226000, s=222000, w=634000, e=638000) ... gs.parse_command("r.univar", map="elevation", format="json") ... finally: ... manager.deactivate()
Caution
To set region within the context, do not call
g.region
, useset_region()
instead.Initializes the MaskManager.
- Parameters:
env – Environment to use. Defaults to modifying
os.environ
.kwargs – Keyword arguments passed to
g.region
- activate()[source]¶
Sets the
GRASS_REGION
environment variable to the generated region name.- Returns:
Returns the
RegionManagerEnv
instance.
- script.append_node_pid(name)[source]¶
Add node name and PID to a name (string)
For the result to be unique, the name needs to be unique within a process. Given that, the result will be unique enough for use in temporary maps and other elements on single machine or an HPC cluster.
The returned string is a name usable for vectors, tables, and columns (vector legal name) as long as provided argument name is.
>>> append_node_pid("tmp_raster_1")
Note
Before you use this function for creating temporary files (i.e., normal files on disk, not maps and other mapset elements), see functions designed for it in the GRASS or standard Python library. These take care of collisions already on different levels.
- script.append_random(name, suffix_length=None, total_length=None)[source]¶
Add a random part to of a specified length to a name (string)
>>> append_random("tmp", 8) >>> append_random("tmp", total_length=16)
Note
Note that this will be influenced by the random seed set for the Python random package.
Note
See the note about creating temporary files in the
append_node_pid()
description.
- script.append_uuid(name)[source]¶
Add UUID4 to a name (string)
To generate a name of an temporary mapset element which is unique in a system, use
append_node_pid()
in a combination with a name unique within your process.To avoid collisions, never shorten the name obtained from this function. A shortened UUID does not have the collision guarantees the full UUID has.
For a random name of a given shorter size, see
append_random()
.>>> append_uuid("tmp")
Note
See the note about creating temporary files in the
append_node_pid()
description.
- script.basename(path: StrPath, ext: str | None = None) str [source]¶
Remove leading directory components and an optional extension from the specified path
- script.clock()[source]¶
Return time counter to measure performance for chunks of code. Should be used only as difference between the calls.
- script.compare_key_value_text_files(filename_a, filename_b, sep=':', val_sep=',', precision=1e-06, proj=False, units=False)[source]¶
Compare two key-value text files
This method will print a warning in case keys that are present in the first file are not present in the second one. The comparison method tries to convert the values into their native format (float, int or string) to allow correct comparison.
An example key-value text file may have this content:
a: Hello b: 1.0 c: 1,2,3,4,5 d : hello,8,0.1
- Parameters:
filename_a (str) – name of the first key-value text file
filename_b (str) – name of the second key-value text file
sep (str) – character that separates the keys and values, default is “:”
val_sep (str) – character that separates the values of a single key, default is “,”
precision (double) – precision with which the floating point values are compared
proj (bool) – True if it has to check some information about projection system
units (bool) – True if it has to check some information about units
- Returns:
True if full or almost identical, False if different
- script.create_environment(gisdbase, location, mapset, env=None)[source]¶
Creates environment to be passed in run_command for example. Returns tuple with temporary file path and the environment. The user of this function is responsible for deleting the file.
- script.create_project(path, name=None, epsg=None, proj4=None, filename=None, wkt=None, datum=None, datum_trans=None, desc=None, overwrite=False)[source]¶
Create new project
- Parameters:
path (str) – path to GRASS database or project; if path to database, project name must be specified with name parameter
name (str) – project name to create
epsg – if given create new project based on EPSG code
proj4 – if given create new project based on Proj4 definition
filename (str) – if given create new project based on georeferenced file
wkt (str) – if given create new project based on WKT definition (can be path to PRJ file or WKT string)
datum – GRASS format datum code
datum_trans – datum transformation parameters (used for epsg and proj4)
desc – description of the project (creates MYNAME file)
overwrite (bool) – True to overwrite project if exists (WARNING: ALL DATA from existing project ARE DELETED!)
- Raises:
ScriptError – Raise
ScriptError
on error
- script.db_connection(force=False, env=None)[source]¶
Return the current database connection parameters (interface to
db.connect -g
).- Example:
>>> db_connection() {'group': '', 'schema': '', 'driver': 'sqlite', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'}
- Parameters:
force – True to set up default DB connection if not defined
env – environment
- Returns:
parsed output of db.connect
- script.db_describe(table, env=None, **args)[source]¶
Return the list of columns for a database table (interface to
db.describe -c
).- Example:
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_describe("myfirestations") {'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22} >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
- Returns:
parsed module output
- script.db_select(sql=None, filename=None, table=None, env=None, **args)[source]¶
Perform SQL select statement
Note
One of sql, filename, or table arguments must be provided.
- Example:
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_select(sql="SELECT cat,CITY FROM myfirestations WHERE cat < 4") (('1', 'Morrisville'), ('2', 'Morrisville'), ('3', 'Apex'))
Simplified usage (it performs
SELECT * FROM myfirestations
.)>>> db_select(table="myfirestations") (('1', '24', 'Morrisville #3', ... 'HS2A', '1.37')) >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
- script.db_table_exist(table, env=None, **args)[source]¶
Check if table exists.
If no driver or database are given, then default settings is used (check db_connection()).
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_table_exist("myfirestations") True >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
table (str) – table name
args
env – environment
- Returns:
True for success, False otherwise
- script.db_table_in_vector(table, mapset='.', env=None)[source]¶
Return the name of vector connected to the table. By default it check only in the current mapset, because the same table name could be used also in other mapset by other vector. It returns None if no vectors are connected to the table.
>>> run_command("g.copy", vector="firestations,myfirestations") 0 >>> db_table_in_vector("myfirestations") ['myfirestations@user1'] >>> db_table_in_vector("mfirestations") >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0
- Parameters:
table (str) – name of table to query
env – environment
- script.debug(msg, debug=1, env=None)[source]¶
Display a debugging message using
g.message -d
.The visibility of a debug message at runtime is controlled by setting the corresponding DEBUG level with
g.gisenv set="DEBUG=X"
(withX
set to the debug level specified in the function call).- Parameters:
msg (str) – debugging message to be displayed
debug (str) – debug level (0-5) with the following recommended levels: - Use 1 for messages generated once of few times, - 3 for messages generated for each raster row or vector line, - 5 for messages generated for each raster cell or vector point.
env – dictionary with system environment variables (
os.environ
by default)
- script.decode(bytes_: AnyStr, encoding: str | None = None) str [source]¶
Decode bytes with default locale and return (unicode) string
No-op if parameter is not bytes (assumed unicode string).
- Parameters:
bytes_ – the bytes to decode
encoding – encoding to be used, default value is None
Example¶
>>> decode(b"Südtirol") u'Südtirol' >>> decode("Südtirol") u'Südtirol' >>> decode(1234) u'1234'
- script.del_temp_region()[source]¶
Unsets WIND_OVERRIDE and removes any region named by it.
See also
The
g.remove
tool
- script.diff_files(filename_a: FileDescriptorOrPath, filename_b: FileDescriptorOrPath) list[str] [source]¶
Diffs two text files and returns difference.
- script.encode(string: AnyStr, encoding: str | None = None) bytes [source]¶
Encode string with default locale and return bytes with that encoding
No-op if parameter is bytes (assumed already encoded). This ensures garbage in, garbage out.
- Parameters:
string – the string to encode
encoding – encoding to be used, default value is None
Example¶
>>> encode(b"Südtirol") b'Südtirol' >>> decode("Südtirol") b'Südtirol' >>> decode(1234) b'1234'
- script.error(msg, env=None)[source]¶
Display an error message using
g.message -e
This function does not end the execution of the program. The right action after the error is up to the caller. For error handling using the standard mechanism use
fatal()
.- Parameters:
msg (str) – error message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.exec_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, env=None, **kwargs)[source]¶
Interface to os.execvpe(), but with the make_command() interface.
- Parameters:
prog (str) – GRASS module
flags (str) – flags to be used (given as a string)
overwrite (bool) – True to enable overwriting the output (
--o
)quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)env – dictionary with system environment variables (
os.environ
by default)kwargs (list) – module’s parameters
- script.fatal(msg, env=None)[source]¶
Display an error message using
g.message -e
, then abort or raiseRaises exception when module global
raise_on_error
is ‘True’, abort (callssys.exit()
) otherwise. Useset_raise_on_error()
to set the behavior.- Parameters:
msg (str) – error message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- Raises:
ScriptError – Raises exception when module global
raise_on_error
is ‘True’
- script.feed_command(*args, **kwargs)[source]¶
Passes all arguments to
start_command()
, but also adds “stdin = PIPE”. Returns thePopen
object.- Parameters:
args (list) – list of unnamed arguments (see
start_command()
for details)kwargs (list) – list of named arguments (see
start_command()
for details)
- Returns:
Popen object
- Return type:
- script.find_file(name, element='cell', mapset=None, env=None)[source]¶
Returns the output from running g.findfile as a dictionary.
Elements in g.findfile refer to mapset directories. However, in parts of the code, different element terms like rast, raster, or rast3d are used. For convenience the function translates such element types to respective mapset elements. Current translations are: “rast”: “cell”, “raster”: “cell”, “rast3d”: “grid3”, “raster3d”: “grid3”, “raster_3d”: “grid3”,
- Example:
>>> result = find_file("elevation", element="cell") >>> print(result["fullname"]) elevation@PERMANENT >>> print(result["file"]) /.../PERMANENT/cell/elevation >>> result = find_file("elevation", element="raster") >>> print(result["fullname"]) elevation@PERMANENT >>> print(result["file"]) /.../PERMANENT/cell/elevation
- Parameters:
- Returns:
parsed output of g.findfile
See also
The
g.findfile
tool
- script.find_program(pgm, *args, env: Mapping[str, str] = None)[source]¶
Attempt to run a program, with optional arguments.
You must call the program in a way that will return a successful exit code. For GRASS modules this means you need to pass it some valid CLI option, like “
--help
”. For other programs a common valid do-little option is usually “--version
”.- Example:
>>> find_program("r.sun", "--help") True >>> find_program("ls", "--version") True
- Parameters:
pgm (str) – program name
args – list of arguments
env – environment
- Returns:
False if the attempt failed due to a missing executable or non-zero return code
- Returns:
True otherwise
- script.float_or_dms(s) float [source]¶
Convert DMS to float.
>>> round(float_or_dms("26:45:30"), 5) 26.75833 >>> round(float_or_dms("26:0:0.1"), 5) 26.00003
- Parameters:
s – DMS value
- Returns:
float value
- script.get_commands(*, env=None)[source]¶
Create list of available GRASS commands to use when parsing string from the command line
- Returns:
list of commands (set) and directory of scripts (collected by extension - MS Windows only)
>>> cmds = list(get_commands()[0]) >>> cmds.sort() >>> cmds[:5] ['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate', 'd.erase']
- script.get_lib_path(modname, libname=None)[source]¶
Return the path of the libname contained in the module.
- script.get_num_suffix(number, max_number)[source]¶
Returns formatted number with number of padding zeros depending on maximum number, used for creating suffix for data series. Does not include the suffix separator.
- Parameters:
number – number to be formatted as map suffix
max_number – maximum number of the series to get number of digits
>>> get_num_suffix(10, 1000) '0010' >>> get_num_suffix(10, 10) '10'
- script.get_raise_on_error()[source]¶
Return True if a
ScriptError
exception is raised instead of callingsys.exit(1)
in case a fatal error was invoked withfatal()
.
- script.get_real_command(cmd)[source]¶
Returns the real file command for a module (cmd)
For Python scripts on MS Windows it returns full path to the script and adds a ‘.py’ extension. For other cases it just returns a module (name). So, you can just use this function for all without further check.
>>> get_real_command("g.region") 'g.region'
- Parameters:
cmd – the command
- script.gisenv(env: Mapping[str, str] | None = None) KeyValue[str | None] [source]¶
Returns the output from running g.gisenv (with no arguments), as a dictionary.
- Example:
>>> env = gisenv() >>> print(env["GISDBASE"]) /opt/grass-data
- Parameters:
env – dictionary with system environment variables (
os.environ
by default)- Returns:
list of GRASS variables
- script.group_to_dict(imagery_group_name, subgroup=None, dict_keys='semantic_labels', dict_values='map_names', fill_semantic_label=True, env=None)[source]¶
Create a dictionary to represent an imagery group with metadata.
Depending on the dict_keys option, the returned dictionary uses either the names of the raster maps (“map_names”), their row indices in the group (“indices”) or their associated semantic_labels (“semantic_labels”) as keys. The default is to use semantic_labels. Note that map metadata of the maps in the group have to be read to get the semantic label, in addition to the group file. The same metadata is read when the “metadata” is requested as dict_values. Other supported dict_values are “map_names” (default), “semantic_labels”, or “indices”.
The function can also operate on the level of subgroups. In case a non-existing (or empty sub-group) is requested a warning is printed and an empty dictionary is returned (following the behavior of i.group).
- Example:
>>> run_command("g.copy", raster="lsat7_2000_10,lsat7_2000_10") >>> run_command("r.support", raster="lsat7_2000_10", semantic_label="L8_1") >>> run_command("g.copy", raster="lsat7_2000_20,lsat7_2000_20") >>> run_command("r.support", raster="lsat7_2000_20", semantic_label="L8_2") >>> run_command("g.copy", raster="lsat7_2000_30,lsat7_2000_30") >>> run_command("r.support", raster="lsat7_2000_30", semantic_label="L8_3") >>> run_command("i.group", group="L8_group", >>> input="lsat7_2000_10,lsat7_2000_20,lsat7_2000_30") >>> group_to_dict("L8_group") {"L8_1": "lsat7_2000_10", ... "L8_3": "lsat7_2000_30"} >>> run_command("g.remove", flags="f", type="group", name="L8_group") >>> run_command("g.remove", flags="f", type="raster", >>> name="lsat7_2000_10,lsat7_2000_20,lsat7_2000_30")
- Parameters:
imagery_group_name (str) – Name of the imagery group to process (or None)
subgroup (str) – Name of the imagery sub-group to process (or None)
dict_keys (str) – What to use as key for dictionary. It can be either “semantic_labels” (default), “map_names” or “indices”
dict_values (str) – What to use as values for dictionary. It can be either “map_names” (default), “semanic_labels”, “indices” or “metadata” (to return dictionaries with full map metadata)
fill_semantic_label (bool) – If maps in a group do not have a semantic label, their index in the group is used instead (default). Otherwise None / “none” is used.
env (dict) – Environment to use when parsing the imagery group
- Returns:
dictionary representing an imagery group with it’s maps and their semantic labels, row indices in the group, or metadata
- Return type:
- script.handle_errors(returncode, result, args, kwargs, handler=None, stderr=None, exception=None, env=None)[source]¶
Error handler for
run_command()
and similar functionsThe functions which are using this function to handle errors, can be typically called with an errors parameter. This function can handle one of the following values: raise, fatal, status, exit, and ignore. The value raise is a default. Alternatively, when this function is called explicitly, the parameter handler can be specified with the same values as errors.
If returncode is 0, result is returned, unless
errors="status"
is set.If kwargs dictionary contains key
errors
, the value is used to determine the return value and the behavior on error. The valueerrors="raise"
is a default in which case aCalledModuleError
exception is raised.For
errors="fatal"
, the function callsfatal()
which has its own rules on what happens next. In this case, env parameter should also be provided unless the caller code relies on a global session. Besides the env parameter, env can be also provided in kwargs.For
errors="status"
, the returncode will be returned. This is useful, e.g., for cases when the exception-based error handling mechanism is not desirable or the return code has some meaning not necessarily interpreted as an error by the caller.For
errors="exit"
,sys.exit()
is called with the returncode, so it behaves similarly to a Bash script withset -e
. No additional error message or exception is produced. This might be useful for a simple script where error message produced by the called module provides sufficient information about what happened to the end user.Finally, for
errors="ignore"
, the value of result will be passed in any case regardless of the returncode.If stderr is provided, it is passed to
CalledModuleError
to build an error message witherrors="raise"
. Witherrors="exit"
, it is printed tosys.stderr
.This function is intended to be used as an error handler or handler of potential errors in code which wraps calling of tools as subprocesses. Typically, this function is not called directly in user code or in a tool code unless the tools are handed directly, e.g., with
Popen
as opposed torun_command()
.- Raises:
If there is an error, and the
errors
parameter is not givenIf the
errors
parameter is given and it is notstatus
,ignore
,fatal
, norexit
.
- script.info(msg, env=None)[source]¶
Display an informational message using
g.message -i
- Parameters:
msg (str) – informational message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.legal_name(s)[source]¶
Checks if the string contains only allowed characters.
This is the Python implementation of
G_legal_filename()
function.Note
It is not clear when exactly use this function, but it might be useful anyway for checking map names and column names.
- script.legalize_vector_name(name, fallback_prefix: str | None = 'x') str [source]¶
Make name usable for vectors, tables, and columns
The returned string is a name usable for vectors, tables, and columns, i.e., it is a vector legal name which is a string containing only lowercase and uppercase ASCII letters, digits, and underscores.
Invalid characters are replaced by underscores. If the name starts with an invalid character, the name is prefixed with fallback_prefix. This increases the length of the resulting name by the length of the prefix.
The fallback_prefix can be empty which is useful when the name is later used as a suffix for some other valid name.
ValueError is raised when provided name is empty or fallback_prefix does not start with a valid character.
- script.list_grouped(type, pattern=None, check_search_path=True, exclude=None, flag='', env=None)[source]¶
List of elements grouped by mapsets.
Returns the output from running g.list, as a dictionary where the keys are mapset names and the values are lists of maps in that mapset.
- Example:
>>> list_grouped("vect", pattern="*roads*")["PERMANENT"] ['railroads', 'roadsmajor']
- Parameters:
type (str) – element type (raster, vector, raster_3d, region, …) or list of elements
pattern (str) – pattern string
check_search_path (str) – True to add mapsets for the search path with no found elements
exclude (str) – pattern string to exclude maps from the research
flag (str) – pattern type: ‘r’ (basic regexp), ‘e’ (extended regexp), or ‘’ (glob pattern)
env – environment
- Returns:
directory of mapsets/elements
See also
The
g.list
tool
- script.list_pairs(type, pattern=None, mapset=None, exclude=None, flag='', env=None)[source]¶
List of elements as pairs
Returns the output from running g.list, as a list of (name, mapset) pairs
- Parameters:
type (str) – element type (raster, vector, raster_3d, region, …)
pattern (str) – pattern string
mapset (str) – mapset name (if not given use search path)
exclude (str) – pattern string to exclude maps from the research
flag (str) – pattern type: ‘r’ (basic regexp), ‘e’ (extended regexp), or ‘’ (glob pattern)
env – environment
- Returns:
list of elements
See also
The
g.list
tool
- script.list_strings(type, pattern=None, mapset=None, exclude=None, flag='', env=None)[source]¶
List of elements as strings.
Returns the output from running g.list, as a list of qualified names.
- Parameters:
type (str) – element type (raster, vector, raster_3d, region, …)
pattern (str) – pattern string
mapset (str) – mapset name (if not given use search path)
exclude (str) – pattern string to exclude maps from the research
flag (str) – pattern type: ‘r’ (basic regexp), ‘e’ (extended regexp), or ‘’ (glob pattern)
env – environment
- Returns:
list of elements
See also
The
g.list
tool
- script.locn_is_latlong(env: Mapping[str, str] | None = None) bool [source]¶
Tests if location is lat/long. Value is obtained by checking the “g.region -pu” projection code.
- Returns:
True for a lat/long region, False otherwise
See also
The
g.region
tool
- script.make_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, errors=None, **options) list[str] [source]¶
Return a list of strings suitable for use as the args parameter to
Popen()
orcall()
.- Example:
>>> make_command("g.message", flags="w", message="this is a warning") ['g.message', '-w', 'message=this is a warning']
The single-character flags are supplied as a string, flags, containing individual flag characters. While an integer for a single flag and a leading dash are also accepted, the best practice is to provide the characters as a string without a leading dash.
- Parameters:
prog (str) – GRASS module
flags (str) – flags to be used (given as a string of flag characters)
overwrite (bool) – True to enable overwriting the output (
--o
)quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)options – module’s parameters
- Returns:
list of arguments
- script.mapcalc(exp, quiet=False, superquiet=False, verbose=False, overwrite=False, seed=None, env=None, **kwargs)[source]¶
Interface to r.mapcalc.
- Parameters:
exp (str) – expression
quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)overwrite (bool) – True to enable overwriting the output (
--o
)seed – an integer used to seed the random-number generator for the rand() function, or ‘auto’ to generate a random seed
env (dict) – dictionary of environment variables for child process
kwargs
- script.mapcalc3d(exp, quiet=False, superquiet=False, verbose=False, overwrite=False, seed=None, env=None, **kwargs)[source]¶
Interface to r3.mapcalc.
- Parameters:
exp (str) – expression
quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)overwrite (bool) – True to enable overwriting the output (
--o
)seed – an integer used to seed the random-number generator for the
rand()
function, or ‘auto’ to generate a random seedenv (dict) – dictionary of environment variables for child process
kwargs
- script.mapcalc_start(exp, quiet=False, superquiet=False, verbose=False, overwrite=False, seed=None, env=None, **kwargs)[source]¶
Interface to r.mapcalc, doesn’t wait for it to finish, returns Popen object.
>>> output = "newele" >>> input = "elevation" >>> expr1 = '"%s" = "%s" * 10' % (output, input) >>> expr2 = "..." # etc. >>> # launch the jobs: >>> p1 = mapcalc_start(expr1) >>> p2 = mapcalc_start(expr2) >>> # wait for them to finish: >>> p1.wait() 0 >>> p2.wait() 1 >>> run_command("g.remove", flags="f", type="raster", name=output)
- Parameters:
exp (str) – expression
quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)overwrite (bool) – True to enable overwriting the output (
--o
)seed – an integer used to seed the random-number generator for the rand() function, or ‘auto’ to generate a random seed
env (dict) – dictionary of environment variables for child process
kwargs
- Returns:
Popen object
- script.mapsets(search_path=False, env=None)[source]¶
List available mapsets
- Parameters:
search_path (bool) – True to list mapsets only in search path
- Returns:
list of mapsets
See also
The
g.mapsets
tool
- script.message(msg, flag=None, env=None)[source]¶
Display a message using
g.message
- Parameters:
msg (str) – message to be displayed
flag (str) – flags (given as string)
env – dictionary with system environment variables (
os.environ
by default)
- script.natural_sort(items)[source]¶
Returns sorted list using natural sort (deprecated, use naturally_sorted)
- script.parse_color(val: str, dflt: tuple[float, float, float] | None = None) tuple[float, float, float] | None [source]¶
Parses the string “val” as a GRASS colour, which can be either one of the named colours or an
R:G:B
tuple e.g.255:255:255
. Returns an (r,g,b) triple whose components are floating point values between 0 and 1.- Example:
>>> parse_color("red") (1.0, 0.0, 0.0) >>> parse_color("255:0:0") (1.0, 0.0, 0.0)
- Parameters:
val – color value
dflt – default color value
- Returns:
tuple RGB
- script.parse_command(*args, **kwargs)[source]¶
Passes all arguments to read_command, then parses the output by default with
parse_key_val()
.If the command has parameter
format
and is called withformat="json"
, the output will be parsed into a dictionary. Similarly, withformat="csv"
the output will be parsed into a list of lists (CSV rows).parse_command("v.db.select", ..., format="json")
Custom parsing function can be optionally given by
parse
parameter including its arguments, e.g.parse_command(..., parse=(gs.parse_key_val, {"sep": ":"}))
Parameter
delimiter
is deprecated.- Parameters:
args – list of unnamed arguments (see
start_command()
for details)kwargs –
list of named arguments (see
start_command()
for details)Deprecated since version 8.4.0: Parameter
delimiter
is deprecated. Use the command’sformat="json"
orformat="csv"
parameter instead
- Returns:
parsed module output
- script.parse_key_val(s: AnyStr, sep: str = '=', dflt: T | None = None, val_type: Callable[[str], T] | None = None, vsep: str | None = None) KeyValue[str | T] | KeyValue[T | None] | KeyValue[T] | KeyValue[str | T | None] [source]¶
Parse a string into a dictionary, where entries are separated by newlines and the key and value are separated by
sep
(default:=
)>>> parse_key_val("min=20\nmax=50") == {"min": "20", "max": "50"} True >>> parse_key_val("min=20\nmax=50", val_type=float) == {"min": 20, "max": 50} True
- Parameters:
s – string to be parsed
sep – key/value separator
dflt – default value to be used
val_type – value type (None for no cast)
vsep – vertical separator (default is Python ‘universal newlines’ approach)
- Returns:
parsed input (dictionary of keys/values)
- script.parser() tuple[dict[str, str], dict[str, bool]] [source]¶
Interface to g.parser, intended to be run from the top-level, e.g.:
if __name__ == "__main__": options, flags = grass.parser() main()
Thereafter, the global variables “options” and “flags” will be dictionaries containing option/flag values, keyed by lower-case option/flag names. The values in “options” are strings, those in “flags” are Python booleans.
Overview table of parser standard options: https://grass.osgeo.org/grass-devel/manuals/parser_standard_options.html
- script.percent(i, n, s, env=None)[source]¶
Display a progress info message using
g.message -p
message(_("Percent complete...")) n = 100 for i in range(n): percent(i, n, 1) percent(1, 1, 1)
- Parameters:
i (int) – current item
n (int) – total number of items
s (int) – increment size
env – dictionary with system environment variables (
os.environ
by default)
- script.pipe_command(*args, **kwargs)[source]¶
Passes all arguments to
start_command()
, but also adds “stdout = PIPE”. Returns thePopen
object.>>> p = pipe_command("g.gisenv") >>> print(p) <....Popen object at 0x...> >>> print(p.communicate()[0]) GISDBASE='/opt/grass-data'; LOCATION_NAME='spearfish60'; MAPSET='glynn'; GUI='text'; MONITOR='x0';
- Parameters:
args (list) – list of unnamed arguments (see
start_command()
for details)kwargs (list) – list of named arguments (see
start_command()
for details)
- Returns:
Popen object
- Return type:
- script.popen_args_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, **kwargs)[source]¶
Split tool name and parameters from Popen parameters
Does the splitting based on known Popen parameter names, and then does the transformation from Python parameters to a list of command line arguments for
Popen
.
- script.raster3d_info(map, env=None)[source]¶
Return information about a raster3d map (interface to
r3.info
).- Example:
>>> mapcalc3d("volume = row() + col() + depth()") >>> raster3d_info("volume") {'vertical_units': '"units"', 'tbres': 1.0, ... 'south': 185000.0} >>> run_command("g.remove", flags="f", type="raster_3d", name="volume") 0
- Parameters:
map (str) – map name
env – environment
- Returns:
parsed raster3d info
- script.raster_history(map, overwrite=False, env=None)[source]¶
Set the command history for a raster map to the command used to invoke the script (interface to
r.support
).- Parameters:
map (str) – map name
env – environment
- Returns:
True on success
- Returns:
False on failure
- script.raster_info(map, env=None)[source]¶
Return information about a raster map (interface to
r.info -gre
).- Example:
>>> raster_info("elevation") {'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}
- Parameters:
map (str) – map name
env – environment
- Returns:
parsed raster info
- script.raster_what(map, coord, env=None, localized=False)[source]¶
Interface to r.what
>>> raster_what("elevation", [[640000, 228000]]) [{'elevation': {'color': '255:214:000', 'label': '', 'value': '102.479'}}]
- script.read_command(*args, **kwargs)[source]¶
Passes all arguments to
pipe_command()
, then waits for the process to complete, returning its stdout (i.e. similar to shellbackticks
).The behavior on error can be changed using errors parameter which is passed to the
handle_errors()
function.- Parameters:
args (list) – list of unnamed arguments (see
start_command()
for details)kwargs (list) – list of named arguments (see
start_command()
for details)
- Returns:
stdout
- script.region(region3d=False, complete=False, env=None)[source]¶
Returns the output from running “g.region -gu”, as a dictionary.
- Example:
>>> curent_region = region() >>> # obtain n, s, e and w values >>> [curent_region[key] for key in "nsew"] [..., ..., ..., ...] >>> # obtain ns and ew resolutions >>> (curent_region["nsres"], curent_region["ewres"]) (..., ...)
- Parameters:
region3d (bool) – True to get 3D region
complete (bool)
env – dictionary with system environment variables (
os.environ
by default)
- Returns:
dictionary of region values
See also
The
g.region
tool
- script.region_env(region3d: bool = False, flags: str | None = None, env: Mapping[str, str] | None = None, **kwargs) str [source]¶
Returns region settings as a string which can used as GRASS_REGION environmental variable.
If no ‘kwargs’ are given then the current region is used. Note that this function doesn’t modify the current region!
See also
See also
use_temp_region()
for alternative method how to define temporary region used for raster-based computation.- Example:
os.environ["GRASS_REGION"] = grass.region_env(region="detail") grass.mapcalc("map=1", overwrite=True) os.environ.pop("GRASS_REGION")
- Parameters:
region3d – True to get 3D region
flags – for example ‘a’
env – dictionary with system environment variables (
os.environ
by default)kwargs – g.region’s parameters like ‘raster’, ‘vector’ or ‘region’
- Returns:
string with region values, or empty string on error
- script.run_command(*args, **kwargs)[source]¶
Execute a module synchronously
This function passes all arguments to
start_command()
, then waits for the process to complete. It is similar tosubprocess.check_call()
, but with themake_command()
interface. By default, an exception is raised in case of a non-zero return code by default.>>> run_command("g.region", raster="elevation")
See
start_command()
for details about parameters and usage.The behavior on error can be changed using errors parameter which is passed to the
handle_errors()
function.- Parameters:
args – unnamed arguments passed to
start_command()
kwargs – named arguments passed to
start_command()
errors (str) – passed to
handle_errors()
Changed in version 8.0: Before 8.0, the function was returning 0 when no error occurred for backward compatibility with code which was checking that value. Now the function returns None, unless
errors="status"
is specified.Changed in version 7.2: In 7.0.0, this function was returning the error code. However, it was rarely checked especially outside of the core code. Additionally,
read_command()
needed a mechanism to report errors as it was used more and more in context which required error handling, Thus, exceptions were introduced as a more expected default behavior for Python programmers. The change was backported to 7.0 series.- Raises:
CalledModuleError – When module returns non-zero return code.
- script.sanitize_mapset_environment(env)[source]¶
Remove environmental variables relevant only for a specific mapset. This should be called when a copy of environment is used with a different mapset.
- script.separator(sep: str) str [source]¶
Returns separator from G_OPT_F_SEP appropriately converted to character.
>>> separator("pipe") '|' >>> separator("comma") ','
If the string does not match any of the separator keywords, it is returned as is:
>>> separator(", ") ', '
- Parameters:
separator (str) – character or separator keyword
- Returns:
separator character
- script.set_capture_stderr(capture=True)[source]¶
Enable capturing standard error output of modules and print it.
By default, standard error output (stderr) of child processes shows in the same place as output of the parent process. This may not always be the same place as
sys.stderr
is written. After calling this function, functions in thegrass.script
package will capture the stderr of child processes and pass it tosys.stderr
if there is an error.Note
This is advantageous for interactive shells such as the one in GUI and interactive notebooks such as Jupyter Notebook.
The capturing can be applied only in certain cases, for example in case of
run_command()
it is applied becauserun_command()
nor its callers do not handle the streams, howeverfeed_command()
cannot do capturing because its callers handle the streams.The previous state is returned. Passing
False
disables the capturing.Added in version 7.4.
See also
- script.set_path(modulename, dirname=None, path='.')[source]¶
Set sys.path looking in the local directory GRASS directories.
- Parameters:
modulename – string with the name of the GRASS module
dirname – string with the directory name containing the python libraries, default None
path – string with the path to reach the dirname locally.
Example¶
“set_path” example working locally with the source code of a module (r.green) calling the function with all the parameters. Below it is reported the directory structure on the r.green module.
grass_prompt> pwd ~/Download/r.green/r.green.hydro/r.green.hydro.financial grass_prompt> tree ../../../r.green ../../../r.green |-- ... |-- libgreen | |-- pyfile1.py | +-- pyfile2.py +-- r.green.hydro |-- Makefile |-- libhydro | |-- pyfile1.py | +-- pyfile2.py |-- r.green.hydro.* +-- r.green.hydro.financial |-- Makefile |-- ... +-- r.green.hydro.financial.py 21 directories, 125 files
in the source code the function is called with the following parameters:
set_path("r.green", "libhydro", "..") set_path("r.green", "libgreen", os.path.join("..", ".."))
when we are executing the module: r.green.hydro.financial locally from the command line:
grass_prompt> python r.green.hydro.financial.py --ui
In this way we are executing the local code even if the module was already installed as grass-addons and it is available in GRASS standards path.
The function is checking if the dirname is provided and if the directory exists and it is available using the path provided as third parameter, if yes add the path to sys.path to be importable, otherwise it will check on GRASS standard paths.
- script.set_raise_on_error(raise_exp=True)[source]¶
Define behavior on fatal error (
fatal()
called)- Parameters:
raise_exp (bool) – True to raise
ScriptError
instead of callingsys.exit(1)
infatal()
- Returns:
current status
- script.split(s)[source]¶
Same shlex.split() func on all OS platforms
We don’t use parameter posix=True on the OS MS Windows due to incorrectly splitting command line parameters:
e.g. d.vect where=”cat < 10”
is split incorrectly as follows:
‘where=”cat’, ‘<’, ‘10”’
Should be:
‘where=cat < 10’
- Parameters:
s (str) – cmd string
return list: cmd list
- script.start_command(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, **kwargs) Popen [source]¶
Returns a
Popen
object with the command created bymake_command()
. Accepts any of the arguments whichPopen()
accepts apart from “args” and “shell”.>>> p = start_command("g.gisenv", stdout=subprocess.PIPE) >>> print(p) <...Popen object at 0x...> >>> print(p.communicate()[0]) GISDBASE='/opt/grass-data'; LOCATION_NAME='spearfish60'; MAPSET='glynn'; GUI='text'; MONITOR='x0';
If the module parameter is the same as Python keyword, add underscore at the end of the parameter. For example, use
lambda_=1.6
instead oflambda=1.6
.- Parameters:
prog (str) – GRASS module
flags (str) – flags to be used (given as a string)
overwrite (bool) – True to enable overwriting the output (
--o
)quiet (bool) – True to run quietly (
--q
)superquiet (bool) – True to run extra quietly (
--qq
)verbose (bool) – True to run verbosely (
--v
)kwargs – module’s parameters
- Returns:
Popen object
- Return type:
- script.tempdir(env=None)[source]¶
Returns the name of a temporary dir, created with g.tempfile.
See also
The
g.tempfile
tool, and thetempfile()
andtempname()
functions
- script.tempfile(create=True, env=None)[source]¶
Returns the name of a temporary file, created with g.tempfile.
- Parameters:
create (bool) – True to create a file
env – environment
- Returns:
path to a tmp file
See also
The
g.tempfile
tool, and thetempdir()
andtempname()
functions
- script.tempname(length: int, lowercase: bool = False) str [source]¶
Generate a GRASS and SQL compliant random name starting with
tmp_
followed by a random part of length “length”- Parameters:
length – length of the random part of the name to generate
lowercase – use only lowercase characters to generate name
- Returns:
String with a random name of length “length” starting with a letter
- Example:
>>> tempname(12) 'tmp_MxMa1kAS13s9'
See also
functions
append_uuid()
,append_random()
, theg.tempfile
tool, and thetempfile()
andtempdir()
functions
- script.text_to_string(text: AnyStr, encoding: str | None = None) str [source]¶
Convert text to str. Useful when passing text into environments, in Python 2 it needs to be bytes on Windows, in Python 3 in needs unicode.
- Parameters:
text – The text to convert to string
encoding – The encoding to be used to decode the text that will be converted
- Returns:
A (unicode) string
- script.try_remove(path: StrOrBytesPath) None [source]¶
Attempt to remove a file; no exception is generated if the attempt fails.
- Parameters:
path (str) – path to file to remove
- script.try_rmdir(path: StrOrBytesPath) None [source]¶
Attempt to remove a directory; no exception is generated if the attempt fails.
- Parameters:
path (str) – path to directory to remove
- script.use_temp_region()[source]¶
Copies the current region to a temporary region with “g.region save=”, then sets WIND_OVERRIDE to refer to that region. Installs an atexit handler to delete the temporary region upon termination.
See also
The
g.region
tool
- script.vector_columns(map, layer=None, getDict=True, env=None, **kwargs)[source]¶
Return a dictionary (or a list) of the columns for the database table connected to a vector map (interface to
v.info -c
).>>> vector_columns("geology", getDict=True) {'PERIMETER': {'index': 2, 'type': 'DOUBLE PRECISION'}, 'GEOL250_': {'index': 3, 'type': 'INTEGER'}, 'SHAPE_area': {'index': 6, 'type': 'DOUBLE PRECISION'}, 'onemap_pro': {'index': 1, 'type': 'DOUBLE PRECISION'}, 'SHAPE_len': {'index': 7, 'type': 'DOUBLE PRECISION'}, 'cat': {'index': 0, 'type': 'INTEGER'}, 'GEOL250_ID': {'index': 4, 'type': 'INTEGER'}, 'GEO_NAME': {'index': 5, 'type': 'CHARACTER'}}
>>> vector_columns("geology", getDict=False) ['cat', 'onemap_pro', 'PERIMETER', 'GEOL250_', 'GEOL250_ID', 'GEO_NAME', 'SHAPE_area', 'SHAPE_len']
- script.vector_db(map, env=None, **kwargs)[source]¶
Return the database connection details for a vector map (interface to
v.db.connect -g
).- Example:
>>> vector_db("geology") {1: {'layer': 1, ... 'table': 'geology'}}
- Parameters:
map (str) – vector map
kwargs – other v.db.connect’s arguments
env – environment
- Returns:
dictionary
- script.vector_db_select(map, layer=1, env=None, **kwargs)[source]¶
Get attribute data of selected vector map layer.
Function returns list of columns and dictionary of values ordered by key column value.
- Example:
>>> print(vector_db_select("geology")["columns"]) ['cat', 'onemap_pro', 'PERIMETER', 'GEOL250_', 'GEOL250_ID', 'GEO_NAME', 'SHAPE_area', 'SHAPE_len'] >>> print(vector_db_select("geology")["values"][3]) ['3', '579286.875', '3335.55835', '4', '3', 'Zml', '579286.829631', '3335.557182'] >>> print(vector_db_select("geology", columns="GEO_NAME")["values"][3]) ['Zml']
- Parameters:
- Returns:
dictionary (‘columns’ and ‘values’)
- script.vector_history(map, replace=False, env=None)[source]¶
Set the command history for a vector map to the command used to invoke the script (interface to
v.support
).
- script.vector_info(map, layer=1, env=None)[source]¶
Return information about a vector map (interface to
v.info
).
- script.vector_info_topo(map, layer=1, env=None)[source]¶
Return information about a vector map (interface to
v.info -t
).
- script.vector_layer_db(map, layer, env=None)[source]¶
Return the database connection details for a vector map layer. If db connection for given layer is not defined, fatal() is called.
- Parameters:
map (str) – map name
layer – layer number
env – environment
- Returns:
parsed output
- script.vector_what(map, coord, distance=0.0, ttype=None, encoding=None, skip_attributes=False, layer=None, multiple=False, env=None)[source]¶
Query vector map at given locations
To query one vector map at one location
print grass.vector_what(map='archsites', coord=(595743, 4925281), distance=250) [{'Category': 8, 'Map': 'archsites', 'Layer': 1, 'Key_column': 'cat', 'Database': '/home/martin/grassdata/spearfish60/PERMANENT/dbf/', 'Mapset': 'PERMANENT', 'Driver': 'dbf', 'Attributes': {'str1': 'No_Name', 'cat': '8'}, 'Table': 'archsites', 'Type': 'Point', 'Id': 8}]
To query one vector map with multiple layers (no additional parameters required)
for q in grass.vector_what(map='some_map', distance=100.0, coord=(596532.357143,4920486.21429)): print q['Map'], q['Layer'], q['Attributes'] new_bug_sites 1 {'str1': 'Beetle_site', 'GRASSRGB': '', 'cat': '80'} new_bug_sites 2 {'cat': '80'}
To query more vector maps at one location
for q in grass.vector_what(map=('archsites', 'roads'), coord=(595743, 4925281), distance=250): print q['Map'], q['Attributes'] archsites {'str1': 'No_Name', 'cat': '8'} roads {'label': 'interstate', 'cat': '1'}
To query one vector map at more locations
for q in grass.vector_what(map='archsites', distance=250, coord=[(595743, 4925281), (597950, 4918898)]): print q['Map'], q['Attributes'] archsites {'str1': 'No_Name', 'cat': '8'} archsites {'str1': 'Bob_Miller', 'cat': '22'}
- Parameters:
map – vector map(s) to query given as string or list/tuple
coord – coordinates of query given as tuple (easting, northing) or list of tuples
distance – query threshold distance (in map units)
ttype – list of topology types (default of v.what are point, line, area, face)
encoding – attributes encoding
skip_attributes – True to skip querying attributes
layer – layer number or list of layers (one for each vector), if None, all layers (-1) are used
multiple – find multiple features within threshold distance
env –
environment
Deprecated since version 8.5.0: Parameter
encoding
is deprecated.
- Returns:
parsed list
- script.verbose(msg, env=None)[source]¶
Display a verbose message using
g.message -v
- Parameters:
msg (str) – verbose message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.verbosity()[source]¶
Return the verbosity level selected by GRASS_VERBOSE
Currently, there are 5 levels of verbosity: -1 nothing will be printed (also fatal errors and warnings will be discarded)
0 only errors and warnings are printed, triggered by “–q” or “–quiet” flag.
1 progress information (percent) and important messages will be printed
2 all messages will be printed
3 also verbose messages will be printed. Triggered by “
--v
” or “--verbose
” flag.
- script.version()[source]¶
Get GRASS version as dictionary
>>> print(version()) {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468', 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)', 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev', 'revision': '53670'}
- script.warning(msg, env=None)[source]¶
Display a warning message using
g.message -w
- Parameters:
msg (str) – warning message to be displayed
env – dictionary with system environment variables (
os.environ
by default)
- script.write_command(*args, **kwargs)[source]¶
Execute a module with standard input given by stdin parameter.
Passes all arguments to
feed_command()
, with the string specified by the stdin argument fed to the process’ standard input.>>> write_command( ... "v.in.ascii", ... input="-", ... stdin="%s|%s" % (635818.8, 221342.4), ... output="view_point", ... ) 0
See
start_command()
for details about parameters and usage.The behavior on error can be changed using errors parameter which is passed to the
handle_errors()
function.- Parameters:
args – unnamed arguments passed to
start_command()
kwargs – named arguments passed to
start_command()
- Returns:
0 with default parameters for backward compatibility only
- Raises:
CalledModuleError – When module returns non-zero return code