script package

Submodules

script.array module

Functions to use GRASS 2D and 3D rasters with NumPy.

Usage:

>>> from __future__ import print_function
>>> import grass.script as gscript
>>> from grass.script import array as garray
>>>
>>> # We create a temporary region that is only valid in this python session
... gscript.use_temp_region()
>>> gscript.run_command("g.region", n=80, e=120, t=60, s=0, w=0, b=0, res=20, res3=20)
0
>>>
>>> # 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.]]
<BLANKLINE>
 [[ 1.  2.  3.  4.  5.  6.]
  [ 2.  3.  4.  5.  6.  7.]
  [ 3.  4.  5.  6.  7.  8.]
  [ 4.  5.  6.  7.  8.  9.]]
<BLANKLINE>
 [[ 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.]]
<BLANKLINE>
 [[1. 2. 0. 1. 2. 0.]
  [2. 0. 1. 2. 0. 1.]
  [0. 1. 2. 0. 1. 2.]
  [1. 2. 0. 1. 2. 0.]]
<BLANKLINE>
 [[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-2012 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[source]

Bases: numpy.memmap

read(mapname, null=None)[source]

Read raster map into array

Parameters:
  • mapname (str) – name of raster map to be read
  • null – null value
Returns:

0 on success

Returns:

non-zero code on failure

Deprecated since version 7.1.

Instead reading the map after creating the array, pass the map name in the array constructor.

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

class script.array.array3d[source]

Bases: numpy.memmap

read(mapname, null=None)[source]

Read 3D raster map into array

Parameters:
  • mapname (str) – name of 3D raster map to be read
  • null – null value
Returns:

0 on success

Returns:

non-zero code on failure

Deprecated since version 7.1.

Instead reading the map after creating the array, pass the map name in the array constructor.

write(mapname, null=None, overwrite=None, quiet=None)[source]

Write array into 3D raster map

Parameters:
  • mapname (str) – name for 3D raster map
  • null – null value
  • overwrite (bool) – True for overwriting existing raster maps
Returns:

0 on success

Returns:

non-zero code on failure

script.core module

Core functions to be used in Python scripts.

Usage:

from grass.script import core as grass
grass.parser()

(C) 2008-2020 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: subprocess.Popen

script.core.call(*args, **kwargs)[source]
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

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 responsile for deleting the file.

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 (path to PRJ file)
  • 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!)
script.core.debug(msg, debug=1)[source]

Display a debugging message using g.message -d

Parameters:
  • msg (str) – debugging message to be displayed
  • debug (str) – debug level (0-5)
script.core.debug_level(force=False)[source]
script.core.del_temp_region()[source]

Unsets WIND_OVERRIDE and removes any region named by it.

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
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
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
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

script.core.find_file(name, element='cell', mapset=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'])  # doctest: +ELLIPSIS
/.../PERMANENT/cell/elevation
Parameters:
  • name (str) – file name
  • element (str) – element type (default ‘cell’)
  • mapset (str) – mapset name (default all mapsets in search path)
Returns:

parsed output of g.findfile

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

script.core.get_capture_stderr()[source]

Return True if stderr is captured, False otherwise.

See set_capture_stderr().

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']
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()

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=None)[source]

Returns the output from running g.gisenv (with no arguments), as a dictionary. Example:

>>> env = gisenv()
>>> print(env['GISDBASE'])  # doctest: +SKIP
/opt/grass-data

:param env run with different environment :return: list of GRASS variables

script.core.handle_errors(returncode, result, args, kwargs)[source]
script.core.info(msg)[source]

Display an informational message using g.message -i

Parameters:msg (str) – informational message to be displayed
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='')[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)
Returns:

directory of mapsets/elements

script.core.list_pairs(type, pattern=None, mapset=None, exclude=None, flag='')[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)
Returns:

list of elements

script.core.list_strings(type, pattern=None, mapset=None, exclude=None, flag='')[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)
Returns:

list of elements

script.core.locn_is_latlong()[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
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

script.core.mapsets(search_path=False)[source]

List available mapsets

Parameters:search_path (bool) – True to list mapsets only in search path
Returns:list of mapsets
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)
script.core.overwrite()[source]

Return True if existing files may be overwritten

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

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

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/grass78/manuals/parser_standard_options.html

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
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)  # doctest: +ELLIPSIS
<....Popen object at 0x...>
>>> print(p.communicate()[0])  # doctest: +SKIP
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

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).

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:

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"]  # doctest: +ELLIPSIS
[..., ..., ..., ...]
>>> # obtain ns and ew resulutions
>>> (curent_region['nsres'], curent_region['ewres'])  # doctest: +ELLIPSIS
(..., ...)
Returns:dictionary of region values
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
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 to subprocess.check_call(), but with the make_command() interface.

For backward compatibility, the function returns exit code by default but only if it is equal to zero. An exception is raised in case of an non-zero return code.

>>> run_command('g.region', raster='elevation')
0

See start_command() for details about parameters and usage.

..note::
You should ignore the return value of this function unless, you change the default behavior using errors parameter.
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.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 the grass.script package will capture the stderr of child processes and pass it to sys.stderr if there is an error.

Note

This is advantages for interactive shells such as the one in GUI and interactive notebooks such as Jupyer 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.

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
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)  # doctest: +ELLIPSIS
<...Popen object at 0x...>
>>> print(p.communicate()[0])  # doctest: +SKIP
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 of lambda=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

script.core.tempdir()[source]

Returns the name of a temporary dir, created with g.tempfile.

script.core.tempfile(create=True)[source]

Returns the name of a temporary file, created with g.tempfile.

Parameters:create (bool) – True to create a file
Returns:path to a tmp file
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'
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.

script.core.verbose(msg)[source]

Display a verbose message using g.message -v

Parameters:msg (str) – verbose message to be displayed
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)[source]

Display a warning message using g.message -w

Parameters:msg (str) – warning message to be displayed
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.

>>> gscript.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.

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_begin_transaction(driver)[source]

Begin transaction.

Returns:SQL command as string
script.db.db_commit_transaction(driver)[source]

Commit transaction.

Returns:SQL command as string
script.db.db_connection(force=False)[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

Returns:parsed output of db.connect
script.db.db_describe(table, **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') # doctest: +ELLIPSIS
{'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) –
Returns:

parsed module output

script.db.db_select(sql=None, filename=None, table=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') # doctest: +ELLIPSIS
(('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 gmod{db.select} arguments
script.db.db_table_exist(table, **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
Returns:

True for success, False otherwise

script.db.db_table_in_vector(table, mapset='.')[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

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.

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
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

script.raster.raster_history(map, overwrite=False)[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
Returns:True on success
Returns:False on failure
script.raster.raster_info(map)[source]

Return information about a raster map (interface to r.info -gre). Example:

>>> raster_info('elevation') # doctest: +ELLIPSIS
{'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}
Parameters:map (str) – map name
Returns:parsed raster info
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

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, 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
script.raster3d.raster3d_info(map)[source]

Return information about a raster3d map (interface to r3.info). Example:

>>> mapcalc3d('volume = row() + col() + depth()')
>>> raster3d_info('volume') # doctest: +ELLIPSIS
{'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
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 GIS database) directory
gisdb = os.path.join(os.path.expanduser("~"), "grassdata")
# the following path is the default path on MS Windows
# gisdb = os.path.join(os.path.expanduser("~"), "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
grass7bin = 'grass78'
if sys.platform.startswith('win'):
    # MS Windows
    grass7bin = r'C:\OSGeo4Win\grass78.bat'
    # uncomment when using standalone WinGRASS installer
    # grass7bin = r'C:\Program Files (x86)\GRASS GIS 7.8.0\grass78.bat'
    # this can be avoided if GRASS executable is added to PATH
elif sys.platform == 'darwin':
    # Mac OS X
    # TODO: this have to be checked, maybe unix way is good enough
    grass7bin = '/Applications/GRASS/GRASS-7.8.app/'

# query GRASS GIS itself for its GISBASE
startcmd = [grass7bin, '--config', 'path']
try:
    p = subprocess.Popen(startcmd, shell=False,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
except OSError as error:
    sys.exit("ERROR: Cannot find GRASS GIS start script"
             " {cmd}: {error}".format(cmd=startcmd[0], error=error))
if p.returncode != 0:
    sys.exit("ERROR: Issues running GRASS GIS start script"
             " {cmd}: {error}"
             .format(cmd=' '.join(startcmd), error=err))
gisbase = out.strip(os.linesep)

# set GISBASE environment variable
os.environ['GISBASE'] = gisbase

# define GRASS-Python environment
grass_pydir = os.path.join(gisbase, "etc", "python")
sys.path.append(grass_pydir)

# import (some) GRASS Python bindings
import grass.script as gscript
import grass.script.setup as gsetup

# launch session
rcfile = gsetup.init(gisbase, gisdb, location, mapset)

# example calls
gscript.message('Current GRASS GIS 7 environment:')
print gscript.gisenv()

gscript.message('Available raster maps:')
for rast in gscript.list_strings(type='raster'):
    print rast

gscript.message('Available vector maps:')
for vect in gscript.list_strings(type='vector'):
    print vect

# clean up at the end
gsetup.cleanup()

(C) 2010-2019 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

script.setup.call(cmd, **kwargs)[source]
script.setup.clean_default_db()[source]
script.setup.clean_temp()[source]
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 gscript

gscript.setup.cleanup()

script.setup.init(gisbase, dbase='', location='demolocation', mapset='PERMANENT')[source]

Initialize system variables to run GRASS modules

This function is for running GRASS GIS without starting it with the standard script grassXY. 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).

To create a GRASS session a gisrc file is created. Caller is responsible for deleting the gisrc file.

Basic usage:

# ... setup GISBASE and PYTHON path before import
import grass.script as gscript
gisrc = gscript.setup.init("/usr/bin/grass7",
                           "/home/john/grassdata",
                           "nc_spm_08", "user1")
# ... use GRASS modules here
# end the session
gscript.setup.finish()
Parameters:
  • gisbase – path to GRASS installation
  • dbase – path to GRASS database (default: ‘’)
  • location – location name (default: ‘demolocation’)
  • mapset – mapset within given location (default: ‘PERMANENT’)
Returns:

path to gisrc file (to be deleted later)

script.setup.set_gui_path()[source]

Insert wxPython GRASS path to sys.path.

script.setup.write_gisrc(dbase, location, mapset)[source]

Write the gisrc file and return its path.

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') # doctest: +NORMALIZE_WHITESPACE
{'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.convert_xml_to_utf8(xml_text)[source]
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 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)
define_first()[source]

Define first parameter

Returns:name of first parameter
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_error_msg()[source]

Get error message (‘’ for no error)

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_keywords()[source]

Get module’s keywords

get_list_flags(element='name')[source]

Get list of flags

Parameters:element (str) – element name
get_list_params(element='name')[source]

Get list of parameters

Parameters:element (str) – element name
get_name()[source]

Get task name

get_options()[source]

Get options

get_param(value, element='name', raiseError=True)[source]

Find and return a param by name

Parameters:
  • value – param’s value
  • element (str) – element name
  • raiseError (bool) – True for raise on error
has_required()[source]

Check if command has at least one required parameter

set_flag(aFlag, aValue, element='value')[source]

Enable / disable flag.

set_options(opts)[source]

Set flags and parameters

:param opts list of flags and parameters

set_param(aParam, aValue, element='value')[source]

Set param value/values.

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
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

get_task()[source]

Get 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]

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
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
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.

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'
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

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'
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
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.natural_sort(l)[source]

Returns sorted strings using natural sort

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)

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
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.

script.utils.split(s)[source]

!Platform specific shlex.split

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.

script.utils.try_remove(path)[source]

Attempt to remove a file; no exception is generated if the attempt fails.

Parameters:path (str) – path to file to remove
script.utils.try_rmdir(path)[source]

Attempt to remove a directory; no exception is generated if the attempt fails.

Parameters:path (str) – path to directory to remove

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, **args)[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) # doctest: +NORMALIZE_WHITESPACE
{'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) # doctest: +NORMALIZE_WHITESPACE
['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
  • args – (v.info’s arguments)
Returns:

dictionary/list of columns

script.vector.vector_db(map, **args)[source]

Return the database connection details for a vector map (interface to v.db.connect -g). Example:

>>> vector_db('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
{1: {'layer': 1, ... 'table': 'geology'}}
Parameters:
  • map (str) – vector map
  • args – other v.db.connect’s arguments
Returns:

dictionary

script.vector.vector_db_select(map, layer=1, **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
Returns:

dictionary (‘columns’ and ‘values’)

script.vector.vector_history(map, replace=False)[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
Returns:

v.support output

script.vector.vector_info(map, layer=1)[source]

Return information about a vector map (interface to v.info). Example:

>>> vector_info('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
{'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917}
Parameters:
  • map (str) – map name
  • layer (int) – layer number
Returns:

parsed vector info

script.vector.vector_info_topo(map, layer=1)[source]

Return information about a vector map (interface to v.info -t). Example:

>>> vector_info_topo('geology') # doctest: +NORMALIZE_WHITESPACE
{'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
Returns:

parsed output

script.vector.vector_layer_db(map, layer)[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
Returns:

parsed output

script.vector.vector_what(map, coord, distance=0.0, ttype=None, encoding=None, skip_attributes=False, layer=None, multiple=False)[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
Returns:

parsed list

Module contents

Python interface to launch GRASS GIS modules in scripts