Note: A new GRASS GIS stable version has been released: GRASS GIS 7.4. Go directly to the new manual page here
Functions to use GRASS 2D and 3D rasters with NumPy.
Usage:
>>> import grass.script as grass
>>> from grass.script import array as garray
>>>
>>> # We create a temporary region that is only valid in this python session
... grass.use_temp_region()
>>> grass.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 and read map2d_1 to modify it
... map2d_2 = garray.array()
>>> # Don't do map2d_2 = map2d_1 % 3
... # because: this will overwrite the internal temporary filename
... map2d_2.read("map2d_1")
0
>>> 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 and read map3d_1 to modify it
... map3d_2 = garray.array3d()
>>> # Don't do map3d_2 = map3d_1 % 3
... # because: this will overwrite the internal temporary filename
... map3d_2.read("map3d_1")
0
>>> 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-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.
Bases: numpy.core.memmap.memmap
Read raster map into array
Parameters: |
|
---|---|
Returns: | 0 on success |
Returns: | non-zero code on failure |
Write array into raster map
Parameters: |
|
---|---|
Returns: | 0 on success |
Returns: | non-zero code on failure |
Core functions to be used in Python scripts.
Usage:
from grass.script import core as grass
grass.parser()
(C) 2008-2014 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.
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: |
|
---|---|
Returns: | True if full or almost identical, False if different |
Create new location
Raise ScriptError on error.
Parameters: |
|
---|
Display a debugging message using g.message -d
Parameters: |
|
---|
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 |
---|
Interface to os.execvpe(), but with the make_command() interface.
Parameters: |
|
---|
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 |
---|
Passes all arguments to start_command(), but also adds “stdin = PIPE”. Returns the Popen object.
Parameters: |
|
---|---|
Returns: | Popen object |
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: |
|
---|---|
Returns: | parsed output of g.findfile |
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: |
|
---|---|
Returns: | False if the attempt failed due to a missing executable or non-zero return code |
Returns: | True otherwise |
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']
Return True if a ScriptError exception is raised instead of calling sys.exit(1) in case a fatal error was invoked with fatal()
Returns the real file commad 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 |
---|
Returns the output from running g.gisenv (with no arguments), as a dictionary. Example:
>>> env = gisenv()
>>> print env['GISDBASE']
/opt/grass-data
Returns: | list of GRASS variables |
---|
Display an informational message using g.message -i
Parameters: | msg (str) – informational message to be displayed |
---|
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.
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: |
|
---|---|
Returns: | directory of mapsets/elements |
List of elements as pairs
Returns the output from running g.list, as a list of (name, mapset) pairs
Parameters: |
|
---|---|
Returns: | list of elements |
List of elements as strings.
Returns the output from running g.list, as a list of qualified names.
Parameters: |
|
---|---|
Returns: | list of elements |
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 |
---|
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: |
|
---|---|
Returns: | list of arguments |
List available mapsets
Parameters: | search_path (bool) – True to list mapsets only in search path |
---|---|
Returns: | list of mapsets |
Display a message using g.message
Parameters: |
|
---|
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: |
|
---|---|
Returns: | tuple RGB |
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: |
|
---|---|
Returns: | parsed module output |
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.
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: |
|
---|
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: |
|
---|---|
Returns: | Popen object |
Passes all arguments to pipe_command, then waits for the process to complete, returning its stdout (i.e. similar to shell backticks).
Parameters: |
|
---|---|
Returns: | stdout |
Returns the output from running “g.region -gu”, as a dictionary. Example:
Parameters: |
|
---|
>>> 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 |
---|
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: |
|
---|
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 |
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.
Parameters: |
|
---|---|
Returns: | 0 with default parameters for backward compatibility only |
Raises: | CalledModuleError when module returns non-zero return code |
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 |
Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file.
mode defaults to os.F_OK | os.X_OK. path defaults to the result of os.environ.get(“PATH”), or can be overridden with a custom search path.
Parameters: |
|
---|
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 of lambda=1.6.
Parameters: |
|
---|---|
Returns: | Popen object |
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 |
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.
Display a verbose message using g.message -v
Parameters: | msg (str) – verbose message to be displayed |
---|
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'}
Display a warning message using g.message -w
Parameters: | msg (str) – warning message to be displayed |
---|
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: |
|
---|---|
Returns: | 0 with default parameters for backward compatibility only |
Raises: | CalledModuleError when module returns non-zero return code |
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.
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 |
---|
Return the list of columns for a database table (interface to db.describe -c). Example:
>>> run_command('g.copy', vector='firestations,myfirestations')
0
>>> db_describe('myfirestations')
{'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22}
>>> run_command('g.remove', flags='f', type='vector', name='myfirestations')
0
Parameters: |
|
---|---|
Returns: | parsed module output |
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: |
|
---|
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: |
|
---|---|
Returns: | True for success, False otherwise |
Return the name of vector connected to the table. 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 |
---|
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.
Interface to r.mapcalc.
Parameters: |
|
---|
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: |
|
---|---|
Returns: | Popen object |
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 |
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 |
---|---|
Returns: | parsed raster info |
Interface to r.what
>>> raster_what('elevation', [[640000, 228000]])
[{'elevation': {'color': '255:214:000', 'label': '', 'value': '102.479'}}]
Parameters: |
|
---|
Raster3d related functions to be used in Python scripts.
Usage:
from grass.script import raster3d as grass
grass.raster3d_info(map)
(C) 2008-2009 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.
Interface to r3.mapcalc.
Parameters: |
|
---|
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 |
---|---|
Returns: | parsed raster3d info |
Setup and initialization functions
Function can be used in Python scripts to setup a GRASS environment without starting an actual GRASS session.
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 = 'grass70'
if sys.platform.startswith('win'):
# MS Windows
grass7bin = r'C:\OSGeo4Win\grass70.bat'
# uncomment when using standalone WinGRASS installer
# grass7bin = r'C:\Program Files (x86)\GRASS GIS 7.0.0\grass70.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.0.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
# delete the rcfile
os.remove(rcfile)
(C) 2010-2012 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>
Initialize system variables to run GRASS modules
This function is for running GRASS GIS without starting it explicitly. No GRASS modules shall be called before call of this function but any module or user script can be called afterwards as if it would be called in an actual GRASS session. 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 (fake) GRASS session a gisrc file is created. Caller is resposible 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
# remove the session's gisrc file to end the session
os.remove(gisrc)
Parameters: |
|
---|---|
Returns: | path to gisrc file (to be deleted later) |
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.
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 |
---|
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) |
---|
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: |
|
---|
Produce an array of command name and arguments for feeding into some execve-like command processor.
Parameters: |
|
---|
Get error string produced by get_cmd(ignoreErrors = False)
Returns: | list of errors |
---|
Get module’s description
Parameters: | full (bool) – True for label + desc |
---|
Find and return a flag by name
Raises ValueError when the flag is not found.
Parameters: | aFlag (str) – name of the flag |
---|
Get list of parameters
Parameters: | element (str) – element name |
---|
Parse interface of given GRASS module
Parameters: |
|
---|
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: |
|
---|---|
Returns: | grassTask instance |
Useful functions to be used in Python scripts.
Usage:
from grass.script import utils as gutils
(C) 2014 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.
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
Remove leading directory components and an optional extension from the specified path
Parameters: |
|
---|
Decode string with defualt locale
Parameters: | string (str) – the string to decode |
---|
Diffs two text files and returns difference.
Parameters: |
|
---|---|
Returns: | list of strings |
Encode string with defualt locale
Parameters: | string (str) – the string to encode |
---|
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 |
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: |
|
---|
>>> get_num_suffix(10, 1000)
'0010'
>>> get_num_suffix(10, 10)
'10'
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: |
|
---|---|
Returns: | parsed input (dictionary of keys/values) |
Returns separator from G_OPT_F_SEP appropriately converted to character.
>>> separator('pipe')
'|'
>>> separator('comma')
','
If the string does not match any of the spearator keywords, it is returned as is:
>>> separator(', ')
', '
Parameters: | separator (str) – character or separator keyword |
---|---|
Returns: | separator character |
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.
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: |
|
---|---|
Returns: | dictionary/list of columns |
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: |
|
---|---|
Returns: | dictionary |
Get attribute data of selected vector map layer.
Function returns list of columns and dictionary of values ordered by key column value. Example:
>>> print vector_db_select('geology')['columns']
['cat', 'onemap_pro', 'PERIMETER', 'GEOL250_', 'GEOL250_ID', 'GEO_NAME', 'SHAPE_area', 'SHAPE_len']
>>> print vector_db_select('geology')['values'][3]
['3', '579286.875', '3335.55835', '4', '3', 'Zml', '579286.829631', '3335.557182']
>>> print vector_db_select('geology', columns = 'GEO_NAME')['values'][3]
['Zml']
Parameters: |
|
---|---|
Returns: | dictionary (‘columns’ and ‘values’) |
Set the command history for a vector map to the command used to invoke the script (interface to v.support).
Parameters: | map (str) – mapname |
---|---|
Returns: | v.support output |
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 |
---|---|
Returns: | parsed vector info |
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 |
---|---|
Returns: | parsed output |
Return the database connection details for a vector map layer. If db connection for given layer is not defined, fatal() is called.
Parameters: |
|
---|---|
Returns: | parsed output |
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: |
|
---|---|
Returns: | parsed list |
Python interface to launch GRASS GIS modules in scripts
Note: A new GRASS GIS stable version has been released: GRASS GIS 7.4. Go directly to the new manual page here
Help Index | Topics Index | Keywords Index | Full Index
© 2003-2018 GRASS Development Team, GRASS GIS 7.0.7svn Reference Manual