grass.script package¶
Python interface to launch GRASS GIS modules in scripts
Submodules¶
grass.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
grass.script.array.
array
(mapname=None, null=None, dtype=<class 'numpy.float64'>, env=None)[source]¶ Bases:
numpy.memmap
Define new numpy array
- Parameters
cls –
dtype – data type (default: numpy.double)
env – environment
-
write
(mapname, title=None, null=None, overwrite=None, quiet=None)[source]¶ Write array into raster map
- Parameters
mapname (str) – name for raster map
title (str) – title for raster map
null – null value
overwrite (bool) – True for overwritting existing raster maps
- Returns
0 on success
- Returns
non-zero code on failure
grass.script.core module¶
Core functions to be used in Python scripts.
Usage:
from grass.script import core as grass
grass.parser()
(C) 2008-2023 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
grass.script.core.
Popen
(args, **kwargs)[source]¶ Bases:
subprocess.Popen
Create new Popen instance.
-
grass.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
filenmae_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
-
grass.script.core.
create_environment
(gisdbase, location, mapset)[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.
-
grass.script.core.
create_location
(dbase, location, epsg=None, proj4=None, filename=None, wkt=None, datum=None, datum_trans=None, desc=None, overwrite=False)[source]¶ Create new location
Raise ScriptError on error.
- Parameters
dbase (str) – path to GRASS database
location (str) – location name to create
epsg – if given create new location based on EPSG code
proj4 – if given create new location based on Proj4 definition
filename (str) – if given create new location based on georeferenced file
wkt (str) – if given create new location 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 location (creates MYNAME file)
overwrite (bool) – True to overwrite location if exists(WARNING: ALL DATA from existing location ARE DELETED!)
-
grass.script.core.
debug
(msg, debug=1)[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” (with X 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.
-
grass.script.core.
del_temp_region
()[source]¶ Unsets WIND_OVERRIDE and removes any region named by it.
-
grass.script.core.
error
(msg)[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
-
grass.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 (<tt>–o</tt>)
quiet (bool) – True to run quietly (<tt>–q</tt>)
verbose (bool) – True to run verbosely (<tt>–v</tt>)
env – directory with environmental variables
kwargs (list) – module’s parameters
-
grass.script.core.
fatal
(msg)[source]¶ Display an error message using g.message -e, then abort or raise
Raises exception when module global raise_on_error is ‘True’, abort (calls exit) otherwise. Use
set_raise_on_error()
to set the behavior.- Parameters
msg (str) – error message to be displayed
-
grass.script.core.
feed_command
(*args, **kwargs)[source]¶ Passes all arguments to start_command(), but also adds “stdin = PIPE”. Returns the Popen 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
-
grass.script.core.
find_file
(name, element='cell', mapset=None, env=None)[source]¶ Returns the output from running g.findfile as a dictionary. Example:
>>> result = find_file('elevation', element='cell') >>> print(result['fullname']) elevation@PERMANENT >>> print(result['file']) /.../PERMANENT/cell/elevation
- Parameters
name (str) – file name
element (str) – element type (default ‘cell’)
mapset (str) – mapset name (default all mapsets in search path)
env – environment
- Returns
parsed output of g.findfile
-
grass.script.core.
find_program
(pgm, *args)[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
- Returns
False if the attempt failed due to a missing executable or non-zero return code
- Returns
True otherwise
-
grass.script.core.
get_capture_stderr
()[source]¶ Return True if stderr is captured, False otherwise.
See set_capture_stderr().
-
grass.script.core.
get_commands
()[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']
-
grass.script.core.
get_raise_on_error
()[source]¶ Return True if a ScriptError exception is raised instead of calling sys.exit(1) in case a fatal error was invoked with fatal()
-
grass.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
-
grass.script.core.
gisenv
(env=None)[source]¶ Returns the output from running g.gisenv (with no arguments), as a dictionary. Example:
>>> env = gisenv() >>> print(env['GISDBASE']) /opt/grass-data
:param env run with different environment :return: list of GRASS variables
-
grass.script.core.
handle_errors
(returncode, result, args, kwargs)[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.
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.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.
-
grass.script.core.
info
(msg)[source]¶ Display an informational message using g.message -i
- Parameters
msg (str) – informational message to be displayed
-
grass.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.
-
grass.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
-
grass.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
-
grass.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
-
grass.script.core.
locn_is_latlong
(env=None)[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
-
grass.script.core.
make_command
(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, errors=None, **options)[source]¶ Return a list of strings suitable for use as the args parameter to Popen() or call(). Example:
>>> make_command("g.message", flags = 'w', message = 'this is a warning') ['g.message', '-w', 'message=this is a warning']
- Parameters
prog (str) – GRASS module
flags (str) – flags to be used (given as a string)
overwrite (bool) – True to enable overwriting the output (<tt>–o</tt>)
quiet (bool) – True to run quietly (<tt>–q</tt>)
verbose (bool) – True to run verbosely (<tt>–v</tt>)
options – module’s parameters
- Returns
list of arguments
-
grass.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
-
grass.script.core.
message
(msg, flag=None)[source]¶ Display a message using g.message
- Parameters
msg (str) – message to be displayed
flag (str) – flags (given as string)
-
grass.script.core.
parse_color
(val, dflt=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
-
grass.script.core.
parse_command
(*args, **kwargs)[source]¶ Passes all arguments to read_command, then parses the output by parse_key_val().
Parsing function can be optionally given by <em>parse</em> parameter including its arguments, e.g.
parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
or you can simply define <em>delimiter</em>
parse_command(..., delimiter = ':')
- Parameters
args – list of unnamed arguments (see start_command() for details)
kwargs – list of named arguments (see start_command() for details)
- Returns
parsed module output
-
grass.script.core.
parser
()[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
-
grass.script.core.
percent
(i, n, s)[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
-
grass.script.core.
pipe_command
(*args, **kwargs)[source]¶ Passes all arguments to start_command(), but also adds “stdout = PIPE”. Returns the Popen 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
-
grass.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 shell backticks).
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
-
grass.script.core.
region
(region3d=False, complete=False, env=None)[source]¶ Returns the output from running “g.region -gu”, as a dictionary. Example:
- Parameters
region3d (bool) – True to get 3D region
complete (bool) –
:param env env
>>> curent_region = region() >>> # obtain n, s, e and w values >>> [curent_region[key] for key in "nsew"] [..., ..., ..., ...] >>> # obtain ns and ew resulutions >>> (curent_region['nsres'], curent_region['ewres']) (..., ...)
- Returns
dictionary of region values
-
grass.script.core.
region_env
(region3d=False, flags=None, env=None, **kwargs)[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
use_temp_region()
for alternative method how to define temporary region used for raster-based computation.- Parameters
region3d (bool) – True to get 3D region
flags (string) – for example ‘a’
env – different environment than current
kwargs – g.region’s parameters like ‘raster’, ‘vector’ or ‘region’
os.environ['GRASS_REGION'] = grass.region_env(region='detail') grass.mapcalc('map=1', overwrite=True) os.environ.pop('GRASS_REGION')
- Returns
string with region values
- Returns
empty string on error
-
grass.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
-
grass.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.
-
grass.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 because run_command() nor its callers do not handle the streams, however feed_command() cannot do capturing because its callers handle the streams.
The previous state is returned. Passing
False
disables the capturing.New in version 7.4.
-
grass.script.core.
set_raise_on_error
(raise_exp=True)[source]¶ Define behaviour on fatal error (fatal() called)
- Parameters
raise_exp (bool) – True to raise ScriptError instead of calling sys.exit(1) in fatal()
- Returns
current status
-
grass.script.core.
start_command
(prog, flags='', overwrite=False, quiet=False, verbose=False, superquiet=False, **kwargs)[source]¶ Returns a Popen object with the command created by make_command. Accepts any of the arguments which Popen() 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 (<tt>–o</tt>)
quiet (bool) – True to run quietly (<tt>–q</tt>)
verbose (bool) – True to run verbosely (<tt>–v</tt>)
kwargs – module’s parameters
- Returns
Popen object
-
grass.script.core.
tempdir
(env=None)[source]¶ Returns the name of a temporary dir, created with g.tempfile.
-
grass.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
-
grass.script.core.
tempname
(length, lowercase=False)[source]¶ Generate a GRASS and SQL compliant random name starting with tmp_ followed by a random part of length “length”
- Parameters
length (int) – length of the random part of the name to generate
lowercase (bool) – use only lowercase characters to generate name
- Returns
String with a random name of length “length” starting with a letter
- Return type
str
- Example
>>> tempname(12) 'tmp_MxMa1kAS13s9'
See also
functions
append_uuid()
,append_random()
-
grass.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.
-
grass.script.core.
verbose
(msg)[source]¶ Display a verbose message using g.message -v
- Parameters
msg (str) – verbose message to be displayed
-
grass.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.
-
grass.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'}
-
grass.script.core.
warning
(msg)[source]¶ Display a warning message using g.message -w
- Parameters
msg (str) – warning message to be displayed
-
grass.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
grass.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.
-
grass.script.db.
db_begin_transaction
(driver)[source]¶ Begin transaction.
- Returns
SQL command as string
-
grass.script.db.
db_commit_transaction
(driver)[source]¶ Commit transaction.
- Returns
SQL command as string
-
grass.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'}
:param force True to set up default DB connection if not defined :param env: environment
- Returns
parsed output of db.connect
-
grass.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
table (str) – table name
args (list) –
env – environment
- Returns
parsed module output
-
grass.script.db.
db_select
(sql=None, filename=None, table=None, env=None, **args)[source]¶ Perform SQL select statement
Note: one of <em>sql</em>, <em>filename</em>, or <em>table</em> arguments must be provided.
Examples:
>>> 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'))
Simplyfied usage (it performs <tt>SELECT * FROM myfirestations</tt>.)
>>> db_select(table = 'myfirestations') (('1', '24', 'Morrisville #3', ... 'HS2A', '1.37')) >>> run_command('g.remove', flags='f', type='vector', name='myfirestations') 0
- Parameters
sql (str) – SQL statement to perform (or None)
filename (str) – name of file with SQL statements (or None)
table (str) – name of table to query (or None)
args (str) – see db.select arguments
env – environment
-
grass.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
-
grass.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
grass.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.
-
grass.script.raster.
mapcalc
(exp, quiet=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 (<tt>–q</tt>)
verbose (bool) – True to run verbosely (<tt>–v</tt>)
overwrite (bool) – True to enable overwriting the output (<tt>–o</tt>)
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 –
-
grass.script.raster.
mapcalc_start
(exp, quiet=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 (<tt>–q</tt>)
verbose (bool) – True to run verbosely (<tt>–v</tt>)
overwrite (bool) – True to enable overwriting the output (<tt>–o</tt>)
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
-
grass.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
-
grass.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
-
grass.script.raster.
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'}}]
- Parameters
map (str) – the map name
coord (list) – a list of list containing all the point that you want query
env –
grass.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.
-
grass.script.raster3d.
mapcalc3d
(exp, quiet=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 (<tt>–q</tt>)
verbose (bool) – True to run verbosely (<tt>–v</tt>)
overwrite (bool) – True to enable overwriting the output (<tt>–o</tt>)
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 –
-
grass.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
grass.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 GIS 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 GIS launch script
# we assume that the GRASS GIS 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
grass8bin = "grass"
if sys.platform.startswith("win"):
# MS Windows
grass8bin = r"C:\OSGeo4W\bin\grass.bat"
# uncomment when using standalone WinGRASS installer
# grass8bin = r'C:\Program Files (x86)\GRASS GIS 8.2.0\grass.bat'
# this can be avoided if GRASS executable is added to PATH
elif sys.platform == "darwin":
# Mac OS X
grass8bin = "/Applications/GRASS-8.2.app/Contents/Resources/bin/grass"
# query GRASS GIS itself for its Python package path
grass_cmd = [grass8bin, "--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
import grass.script.setup as gsetup
# launch session
rcfile = gsetup.init(gisdb, location, mapset)
# example calls
gs.message("Current GRASS GIS 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
gsetup.finish()
(C) 2010-2022 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
grass.script.setup.
SessionHandle
(active=True)[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 import grass.script.setup 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 import grass.script.setup with gs.setup.init("~/grassdata/nc_spm_08/user1"): # ... use GRASS modules here # session ends automatically here
-
property
active
¶ True if session is active (not finished)
-
property
-
grass.script.setup.
call
(cmd, **kwargs)[source]¶ Wrapper for subprocess.call to deal with platform-specific issues
-
grass.script.setup.
finish
()[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.
-
grass.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 GIS 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.
-
grass.script.setup.
init
(path, location=None, mapset=None, grass_path=None)[source]¶ Initialize system variables to run GRASS modules
This function is for running GRASS GIS 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. Caller is responsible for deleting the file which is normally done with the function
finish()
.Basic usage:
# ... setup GISBASE and sys.path before import import grass.script as gs gs.setup.init( "~/grassdata/nc_spm_08/user1", grass_path="/usr/lib/grass", ) # ... use GRASS modules here # end the session gs.setup.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
- 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
grass.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.
-
grass.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
-
grass.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
-
grass.script.task.
cmdtuple_to_list
(cmd)[source]¶ Convert command tuple to list.
- Parameters
cmd (tuple) – GRASS command to be converted
- Returns
command in list
-
grass.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
-
grass.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)
-
class
grass.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
ignoreErrors (bool) – True to return whatever has been built so far, even though it would not be a correct command for GRASS
ignoreRequired (bool) – True to ignore required flags, otherwise ‘@<required@>’ is shown
ignoreDefault (bool) – True to ignore parameters with default values
-
get_cmd_error
()[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
-
get_list_params
(element='name')[source]¶ Get list of parameters
- Parameters
element (str) – element name
-
grass.script.task.
parse_interface
(name, parser=<class 'grass.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 –
-
class
grass.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
grass.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
grass.script.utils.
KeyValue
[source]¶ Bases:
dict
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
-
grass.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 GIS or standard Python library. These take care of collisions already on different levels.
-
grass.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 influeced by the random seed set for the Python random package.
..note:
See the note about creating temporary files in the :func:`append_node_pid()` description.
-
grass.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 :func:`append_node_pid()` description.
-
grass.script.utils.
basename
(path, ext=None)[source]¶ Remove leading directory components and an optional extension from the specified path
- Parameters
path (str) – path
ext (str) – extension
-
grass.script.utils.
clock
()[source]¶ Return time counter to measure performance for chunks of code. Uses time.clock() for Py < 3.3, time.perf_counter() for Py >= 3.3. Should be used only as difference between the calls.
-
grass.script.utils.
decode
(bytes_, encoding=None)[source]¶ Decode bytes with default locale and return (unicode) string
No-op if parameter is not bytes (assumed unicode string).
- Parameters
bytes (bytes) – the bytes to decode
encoding – encoding to be used, default value is None
>>> decode(b'Südtirol') u'Südtirol' >>> decode(u'Südtirol') u'Südtirol' >>> decode(1234) u'1234'
-
grass.script.utils.
diff_files
(filename_a, filename_b)[source]¶ Diffs two text files and returns difference.
- Parameters
filename_a (str) – first file path
filename_b (str) – second file path
- Returns
list of strings
-
grass.script.utils.
encode
(string, encoding=None)[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 (str) – the string to encode
encoding – encoding to be used, default value is None
>>> encode(b'Südtirol') b'Südtirol' >>> decode(u'Südtirol') b'Südtirol' >>> decode(1234) b'1234'
-
grass.script.utils.
float_or_dms
(s)[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
-
grass.script.utils.
get_lib_path
(modname, libname=None)[source]¶ Return the path of the libname contained in the module.
-
grass.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'
-
grass.script.utils.
legalize_vector_name
(name, fallback_prefix='x')[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.
-
grass.script.utils.
natural_sort
(items)[source]¶ Returns sorted list using natural sort (deprecated, use naturally_sorted)
-
grass.script.utils.
naturally_sorted
(items, key=None)[source]¶ Returns sorted list using natural sort
-
grass.script.utils.
parse_key_val
(s, sep='=', dflt=None, val_type=None, vsep=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 (str) – string to be parsed
sep (str) – 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)
-
grass.script.utils.
separator
(sep)[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
-
grass.script.utils.
set_path
(modulename, dirname=None, path='.')[source]¶ Set sys.path looking in the 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.
“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 cheching 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 GIS standard paths.
-
grass.script.utils.
text_to_string
(text, encoding=None)[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.
grass.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.
-
grass.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']
- Parameters
map (str) – map name
layer – layer number or name (None for all layers)
getDict (bool) – True to return dictionary of columns otherwise list of column names is returned
kwargs – (v.info’s arguments)
env – environment
- Returns
dictionary/list of columns
-
grass.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
-
grass.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
map (str) – map name
layer (int) – layer number
kwargs – v.db.select options
env – environment
- Returns
dictionary (‘columns’ and ‘values’)
-
grass.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).
- Parameters
map (str) – mapname
replace (bool) – Replace command line instead of appending it
env – environment
- Returns
v.support output
-
grass.script.vector.
vector_info
(map, layer=1, env=None)[source]¶ Return information about a vector map (interface to v.info). Example:
>>> vector_info('geology') {'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917}
- Parameters
map (str) – map name
layer (int) – layer number
env – environment
- Returns
parsed vector info
-
grass.script.vector.
vector_info_topo
(map, layer=1, env=None)[source]¶ Return information about a vector map (interface to v.info -t). Example:
>>> vector_info_topo('geology') {'lines': 0, 'centroids': 1832, 'boundaries': 3649, 'points': 0, 'primitives': 5481, 'islands': 907, 'nodes': 2724, 'map3d': False, 'areas': 1832}
- Parameters
map (str) – map name
layer (int) – layer number
env – environment
- Returns
parsed output
-
grass.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
-
grass.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 quering 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
- Returns
parsed list