GRASS Programmer's Manual  6.4.2(2012)
python::core Namespace Reference

Data Structures

class  Popen
class  ScriptError

Functions

def call
def decode
def make_command
 Return a list of strings suitable for use as the args parameter to Popen() or call().
def start_command
 Returns a Popen object with the command created by make_command.
def run_command
 Passes all arguments to start_command(), then waits for the process to complete, returning its exit code.
def pipe_command
 Passes all arguments to start_command(), but also adds "stdout = PIPE".
def feed_command
 Passes all arguments to start_command(), but also adds "stdin = PIPE".
def read_command
 Passes all arguments to pipe_command, then waits for the process to complete, returning its stdout (i.e.
def parse_command
 Passes all arguments to read_command, then parses the output by parse_key_val().
def write_command
 Passes all arguments to feed_command, with the string specified by the 'stdin' argument fed to the process' stdin.
def exec_command
 Interface to os.execvpe(), but with the make_command() interface.
def message
 Display a message using `g.message`.
def debug
 Display a debugging message using `g.message -d`.
def verbose
 Display a verbose message using `g.message -v`.
def info
 Display an informational message using `g.message -i`.
def percent
 Display a progress info message using `g.message -p`.
def warning
 Display a warning message using `g.message -w`.
def error
 Display an error message using `g.message -e`.
def fatal
 Display an error message using `g.message -e`, then abort.
def set_raise_on_error
 Define behaviour on error (error() called)
def parser
 Interface to g.parser, intended to be run from the top-level, e.g.
def tempfile
 Returns the name of a temporary file, created with g.tempfile.
def tempdir
 Returns the name of a temporary dir, created with g.tempfile.
def parse_key_val
 Parse a string into a dictionary, where entries are separated by newlines and the key and value are separated by `sep' (default: `=')
def gisenv
 Returns the output from running g.gisenv (with no arguments), as a dictionary.
def region
 Returns the output from running "g.region -g", as a dictionary.
def use_temp_region
 Copies the current region to a temporary region with "g.region save=", then sets WIND_OVERRIDE to refer to that region.
def del_temp_region
 Unsets WIND_OVERRIDE and removes any region named by it.
def find_file
 Returns the output from running g.findfile as a dictionary.
def list_grouped
 List elements grouped by mapsets.
def list_pairs
 List of elements as tuples.
def list_strings
 List of elements as strings.
def mlist_grouped
 List of elements grouped by mapsets.
def parse_color
 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.
def overwrite
 Return True if existing files may be overwritten.
def verbosity
 Return the verbosity level selected by GRASS_VERBOSE.
def basename
 various utilities, not specific to GRASS
def find_program
 Attempt to run a program, with optional arguments.
def try_remove
 Attempt to remove a file; no exception is generated if the attempt fails.
def try_rmdir
 Attempt to remove a directory; no exception is generated if the attempt fails.
def float_or_dms
 Convert DMS to float.
def mapsets
 List available mapsets.
def create_location
 Create new location.
def version
 Get GRASS version as dictionary.

Variables

 PIPE = subprocess.PIPE
 STDOUT = subprocess.STDOUT
 raise_on_error = False
int debug_level = 0
list _popen_args
dictionary named_colors

Function Documentation

def python.core.basename (   path,
  ext = None 
)

various utilities, not specific to GRASS

Remove leading directory components and an optional extension from the specified path

Parameters:
pathpath
extextension

Definition at line 796 of file core.py.

Referenced by parser().

def python.core.call (   args,
  kwargs 
)

Definition at line 71 of file core.py.

Referenced by find_program().

def python.core.create_location (   dbase,
  location,
  epsg = None,
  proj4 = None,
  filename = None,
  wkt = None,
  datum = None,
  desc = None 
)

Create new location.

Raise ScriptError on error.

Parameters:
dbasepath to GRASS database
locationlocation name to create
epgsif given create new location based on EPSG code
proj4if given create new location based on Proj4 definition
filenameif given create new location based on georeferenced file
wktif given create new location based on WKT definition (path to PRJ file)
datumdatum transformation parameters (used for epsg and proj4)
descdescription of the location (creates MYNAME file)

Definition at line 894 of file core.py.

References gisenv(), pipe_command(), and run_command().

def python.core.debug (   msg,
  debug = 1 
)

Display a debugging message using `g.message -d`.

Parameters:
msgdebugging message to be displayed
debugdebug level (0-5)

Definition at line 324 of file core.py.

References run_command().

Referenced by python::vector.vector_db_select().

Unsets WIND_OVERRIDE and removes any region named by it.

Definition at line 572 of file core.py.

References run_command().

def python.core.error (   msg)

Display an error message using `g.message -e`.

Raise exception when on_error is 'raise'.

Parameters:
msgerror message to be displayed

Definition at line 370 of file core.py.

References message().

Referenced by fatal().

def python.core.exec_command (   prog,
  flags = "",
  overwrite = False,
  quiet = False,
  verbose = False,
  env = None,
  kwargs 
)

Interface to os.execvpe(), but with the make_command() interface.

Parameters:
progGRASS module
flagsflags to be used (given as a string)
overwriteTrue to enable overwriting the output (--o)
quietTrue to run quietly (--q)
verboseTrue to run verbosely (--v)
envdirectory with enviromental variables
kwargsmodule's parameters

Definition at line 297 of file core.py.

References make_command().

def python.core.fatal (   msg)

Display an error message using `g.message -e`, then abort.

Parameters:
msgerror message to be displayed

Definition at line 383 of file core.py.

References error().

Referenced by python::db.db_describe(), python::db.db_select(), python::raster.mapcalc(), mapsets(), and python::vector.vector_layer_db().

def python.core.feed_command (   args,
  kwargs 
)

Passes all arguments to start_command(), but also adds "stdin = PIPE".

Returns the Popen object.

Parameters:
argslist of unnamed arguments (see start_command() for details)
kwargslist of named arguments (see start_command() for details)
Returns:
Popen object

Definition at line 217 of file core.py.

References start_command().

Referenced by write_command().

def python.core.find_file (   name,
  element = 'cell',
  mapset = None 
)

Returns the output from running g.findfile as a dictionary.

Example:

>>> result = grass.find_file('fields', element = 'vector')
>>> print result['fullname']
fields@PERMANENT
>>> print result['file']
/opt/grass-data/spearfish60/PERMANENT/vector/fields
Parameters:
namefile name
elementelement type (default 'cell')
mapsetmapset name (default all mapsets in search path)
Returns:
parsed output of g.findfile

Definition at line 582 of file core.py.

References parse_key_val(), and read_command().

def python.core.find_program (   pgm,
  args = [] 
)

Attempt to run a program, with optional arguments.

Parameters:
pgmprogram name
argslist of arguments
Returns:
False if the attempt failed due to a missing executable
True otherwise

Definition at line 813 of file core.py.

References call().

Referenced by version().

Convert DMS to float.

Parameters:
sDMS value
Returns:
float value

Definition at line 861 of file core.py.

Referenced by python::raster.raster_info().

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

Example:

>>> env = grass.gisenv()
>>> print env['GISDBASE']
/opt/grass-data
Returns:
list of GRASS variables

Definition at line 525 of file core.py.

References parse_key_val(), and read_command().

Referenced by create_location(), python::raster.raster_history(), and version().

def python.core.info (   msg)

Display an informational message using `g.message -i`.

Parameters:
msginformational message to be displayed

Definition at line 339 of file core.py.

References message().

Referenced by MT_tree_info_new().

def python.core.list_grouped (   type,
  check_search_path = True 
)

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

>>> grass.list_grouped('rast')['PERMANENT']
['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
Parameters:
typeelement type (rast, vect, rast3d, region, ...)
check_search_pathTrue to add mapsets for the search path with no found elements
Returns:
directory of mapsets/elements

Definition at line 605 of file core.py.

References mapsets(), and read_command().

Referenced by list_pairs().

def python.core.list_pairs (   type)

List of elements as tuples.

Returns the output from running g.list, as a list of (map, mapset) pairs. Example:

>>> grass.list_pairs('rast')
[('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
Parameters:
typeelement type (rast, vect, rast3d, region, ...)
Returns:
list of tuples (map, mapset)

Definition at line 652 of file core.py.

References list_grouped().

Referenced by list_strings().

def python.core.list_strings (   type)

List of elements as strings.

Returns the output from running g.list, as a list of qualified names. Example:

>>> grass.list_strings('rast')
['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
Parameters:
typeelement type
Returns:
list of strings ('map@mapset')

Definition at line 670 of file core.py.

References list_pairs().

def python.core.make_command (   prog,
  flags = "",
  overwrite = False,
  quiet = False,
  verbose = False,
  options 
)

Return a list of strings suitable for use as the args parameter to Popen() or call().

Example:

>>> grass.make_command("g.message", flags = 'w', message = 'this is a warning')
['g.message', '-w', 'message=this is a warning']
Parameters:
progGRASS module
flagsflags to be used (given as a string)
overwriteTrue to enable overwriting the output (--o)
quietTrue to run quietly (--q)
verboseTrue to run verbosely (--v)
optionsmodule's parameters
Returns:
list of arguments

Definition at line 97 of file core.py.

Referenced by exec_command(), and start_command().

def python.core.mapsets (   search_path = False)

List available mapsets.

Parameters:
searchPatchTrue to list mapsets only in search path
Returns:
list of mapsets

Definition at line 872 of file core.py.

References fatal(), and read_command().

Referenced by G_available_mapsets(), list_grouped(), list_mapsets(), and mlist_grouped().

def python.core.message (   msg,
  flag = None 
)

Display a message using `g.message`.

Parameters:
msgmessage to be displayed
flagflags (given as string)

Definition at line 316 of file core.py.

References run_command().

Referenced by error(), info(), percent(), verbose(), and warning().

def python.core.mlist_grouped (   type,
  pattern = None,
  check_search_path = True 
)

List of elements grouped by mapsets.

Returns the output from running g.mlist, as a dictionary where the keys are mapset names and the values are lists of maps in that mapset. Example:

>>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
['railroads', 'roads', 'rstrct.areas', 'rushmore']
Parameters:
typeelement type (rast, vect, rast3d, region, ...)
patternpattern string
check_search_pathTrue to add mapsets for the search path with no found elements
Returns:
directory of mapsets/elements

Definition at line 689 of file core.py.

References mapsets(), read_command(), and warning().

Return True if existing files may be overwritten.

Definition at line 777 of file core.py.

def python.core.parse_color (   val,
  dflt = None 
)

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:

>>> grass.parse_color("red")
(1.0, 0.0, 0.0)
>>> grass.parse_color("255:0:0")
(1.0, 0.0, 0.0)
Parameters:
valcolor value
dfltdefault color value
Returns:
tuple RGB

Definition at line 748 of file core.py.

def python.core.parse_command (   args,
  kwargs 
)

Passes all arguments to read_command, then parses the output by parse_key_val().

Parsing function can be optionally given by parse parameter including its arguments, e.g.

parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))

or you can simply define delimiter

parse_command(..., delimiter = ':')
Parameters:
argslist of unnamed arguments (see start_command() for details)
kwargslist of named arguments (see start_command() for details)
Returns:
parsed module output

Definition at line 241 of file core.py.

References read_command(), and gui_modules::psmap_dialogs.type.

Referenced by version().

def python.core.parse_key_val (   s,
  sep = '=',
  dflt = None,
  val_type = None,
  vsep = None 
)

Parse a string into a dictionary, where entries are separated by newlines and the key and value are separated by `sep' (default: `=')

Parameters:
sstring to be parsed
sepkey/value separator
dfltdefault value to be used
val_typevalue type (None for no cast)
vsepvertical separator (default os.linesep)
Returns:
parsed input (dictionary of keys/values)

Definition at line 484 of file core.py.

Referenced by python::db.db_connection(), find_file(), gisenv(), python::raster.raster_info(), region(), and python::vector.vector_info_topo().

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.

Definition at line 428 of file core.py.

References basename().

Referenced by python::task.parse_interface().

def python.core.percent (   i,
  n,
  s 
)

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:
icurrent item
ntotal number of items
sincrement size

Definition at line 346 of file core.py.

References message().

def python.core.pipe_command (   args,
  kwargs 
)

Passes all arguments to start_command(), but also adds "stdout = PIPE".

Returns the Popen object.

>>> p = grass.pipe_command("g.gisenv")
>>> print p
<subprocess.Popen object at 0xb7c12f6c>
>>> print p.communicate()[0]
GISDBASE='/opt/grass-data';
LOCATION_NAME='spearfish60';
MAPSET='glynn';
GRASS_DB_ENCODING='ascii';
GRASS_GUI='text';
MONITOR='x0';
Parameters:
argslist of unnamed arguments (see start_command() for details)
kwargslist of named arguments (see start_command() for details)
Returns:
Popen object

Definition at line 192 of file core.py.

References start_command().

Referenced by create_location(), and read_command().

def python.core.read_command (   args,
  kwargs 
)

Passes all arguments to pipe_command, then waits for the process to complete, returning its stdout (i.e.

similar to shell `backticks`).

Parameters:
argslist of unnamed arguments (see start_command() for details)
kwargslist of named arguments (see start_command() for details)
Returns:
stdout

Definition at line 229 of file core.py.

References pipe_command().

Referenced by python::db.db_connection(), python::db.db_describe(), find_file(), gisenv(), list_grouped(), mapsets(), mlist_grouped(), parse_command(), python::raster.raster_info(), region(), tempdir(), tempfile(), python::vector.vector_columns(), python::vector.vector_db(), python::vector.vector_db_select(), python::vector.vector_info_topo(), and python::vector.vector_what().

Returns the output from running "g.region -g", as a dictionary.

Example:

>>> region = grass.region()
>>> [region[key] for key in "nsew"]
[228500.0, 215000.0, 645000.0, 630000.0]
>>> (region['nsres'], region['ewres'])
(10.0, 10.0)
Returns:
dictionary of region values

Definition at line 542 of file core.py.

References parse_key_val(), and read_command().

def python.core.run_command (   args,
  kwargs 
)

Passes all arguments to start_command(), then waits for the process to complete, returning its exit code.

Similar to subprocess.call(), but with the make_command() interface.

Parameters:
argslist of unnamed arguments (see start_command() for details)
kwargslist of named arguments (see start_command() for details)
Returns:
exit code (0 for success)

Definition at line 179 of file core.py.

References start_command().

Referenced by create_location(), python::db.db_select(), debug(), del_temp_region(), message(), python::raster.raster_history(), use_temp_region(), and python::vector.vector_history().

def python.core.set_raise_on_error (   raise_exp = True)

Define behaviour on error (error() called)

Parameters:
raise_expTrue to raise ScriptError instead of calling error()
Returns:
current status

Definition at line 391 of file core.py.

def python.core.start_command (   prog,
  flags = "",
  overwrite = False,
  quiet = False,
  verbose = False,
  kwargs 
)

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 = grass.start_command("g.gisenv", stdout = subprocess.PIPE)
>>> print p
<subprocess.Popen object at 0xb7c12f6c>
>>> print p.communicate()[0]
GISDBASE='/opt/grass-data';
LOCATION_NAME='spearfish60';
MAPSET='glynn';
GRASS_DB_ENCODING='ascii';
GRASS_GUI='text';
MONITOR='x0';
Parameters:
progGRASS module
flagsflags to be used (given as a string)
overwriteTrue to enable overwriting the output (--o)
quietTrue to run quietly (--q)
verboseTrue to run verbosely (--v)
kwargsmodule's parameters
Returns:
Popen object

Definition at line 133 of file core.py.

References make_command().

Referenced by feed_command(), pipe_command(), and run_command().

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

Definition at line 474 of file core.py.

References read_command(), and try_remove().

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

Definition at line 470 of file core.py.

References read_command().

def python.core.try_remove (   path)

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

Parameters:
pathpath to file to remove

Definition at line 837 of file core.py.

Referenced by python::db.db_select(), and tempdir().

def python.core.try_rmdir (   path)

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

Parameters:
pathpath to directory to remove

Definition at line 850 of file core.py.

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.

Definition at line 562 of file core.py.

References run_command().

def python.core.verbose (   msg)

Display a verbose message using `g.message -v`.

Parameters:
msgverbose message to be displayed

Definition at line 332 of file core.py.

References message().

Return the verbosity level selected by GRASS_VERBOSE.

Definition at line 784 of file core.py.

Get GRASS version as dictionary.

print version()

{'date': '2011', 'libgis_date': '2011-04-13 13:19:03 +0200 (Wed, 13 Apr 2011)',
'version': '6.4.2svn', 'libgis_revision': '45934', 'revision': '47445'}

Definition at line 1024 of file core.py.

References find_program(), gisenv(), and parse_command().

Referenced by main().

def python.core.warning (   msg)

Display a warning message using `g.message -w`.

Parameters:
msgwarning message to be displayed

Definition at line 363 of file core.py.

References message().

Referenced by mlist_grouped(), and python::raster.raster_history().

def python.core.write_command (   args,
  kwargs 
)

Passes all arguments to feed_command, with the string specified by the 'stdin' argument fed to the process' stdin.

Parameters:
argslist of unnamed arguments (see start_command() for details)
kwargslist of named arguments (see start_command() for details)
Returns:
return code

Definition at line 282 of file core.py.

References feed_command().

Referenced by python::raster.mapcalc().


Variable Documentation

Initial value:
00001 ["bufsize", "executable", "stdin", "stdout", "stderr",
00002                "preexec_fn", "close_fds", "cwd", "env",
00003                "universal_newlines", "startupinfo", "creationflags"]

Definition at line 76 of file core.py.

Definition at line 69 of file core.py.

Referenced by dig_angle_next_line(), and dig_build_area_with_line().

Initial value:
00001 {
00002     "white":   (1.00, 1.00, 1.00),
00003     "black":   (0.00, 0.00, 0.00),
00004     "red":     (1.00, 0.00, 0.00),
00005     "green":   (0.00, 1.00, 0.00),
00006     "blue":    (0.00, 0.00, 1.00),
00007     "yellow":  (1.00, 1.00, 0.00),
00008     "magenta": (1.00, 0.00, 1.00),
00009     "cyan":    (0.00, 1.00, 1.00),
00010     "aqua":    (0.00, 0.75, 0.75),
00011     "grey":    (0.75, 0.75, 0.75),
00012     "gray":    (0.75, 0.75, 0.75),
00013     "orange":  (1.00, 0.50, 0.00),
00014     "brown":   (0.75, 0.50, 0.25),
00015     "purple":  (0.50, 0.00, 1.00),
00016     "violet":  (0.50, 0.00, 1.00),
00017     "indigo":  (0.00, 0.50, 1.00)}

Definition at line 730 of file core.py.

Definition at line 58 of file core.py.

Definition at line 68 of file core.py.

python::core::STDOUT = subprocess.STDOUT

Definition at line 59 of file core.py.

 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines