[GRASS-SVN] r61917 - grass/trunk/lib/python/script
svn_grass at osgeo.org
svn_grass at osgeo.org
Sat Sep 13 14:45:23 PDT 2014
Author: lucadelu
Date: 2014-09-13 14:45:23 -0700 (Sat, 13 Sep 2014)
New Revision: 61917
Modified:
grass/trunk/lib/python/script/array.py
grass/trunk/lib/python/script/core.py
grass/trunk/lib/python/script/db.py
grass/trunk/lib/python/script/raster.py
grass/trunk/lib/python/script/raster3d.py
grass/trunk/lib/python/script/task.py
grass/trunk/lib/python/script/utils.py
grass/trunk/lib/python/script/vector.py
Log:
python script library: update documentation and doctest; fix pep8
Modified: grass/trunk/lib/python/script/array.py
===================================================================
--- grass/trunk/lib/python/script/array.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/array.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -1,30 +1,25 @@
-"""!@package grass.script.array
-
- at brief GRASS Python scripting module (2D and 3D raster with numpy)
-
+"""
Functions to use GRASS 2D and 3D rasters with NumPy.
Usage:
- at code
-
>>> 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.]
@@ -36,7 +31,7 @@
... map2d_1.write(mapname="map2d_1", overwrite=True)
100%
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
@@ -54,30 +49,28 @@
... map2d_2.write(mapname="map2d_2", overwrite=True)
100%
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.]
@@ -101,12 +94,10 @@
[ 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.]
@@ -117,14 +108,12 @@
100%
0
- at endcode
-
(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.
- at author Glynn Clements
+.. sectionauthor:: Glynn Clements
"""
import os
@@ -138,10 +127,10 @@
class array(numpy.memmap):
def __new__(cls, dtype=numpy.double):
- """!Define new numpy array
+ """Define new numpy array
- @param cls
- @param dtype data type (default: numpy.double)
+ :param cls:
+ :param dtype: data type (default: numpy.double)
"""
reg = grass.region()
r = reg['rows']
@@ -166,13 +155,13 @@
try_remove(self.filename)
def read(self, mapname, null=None):
- """!Read raster map into array
+ """Read raster map into array
- @param mapname name of raster map to be read
- @param null null value
+ :param str mapname: name of raster map to be read
+ :param null: null value
- @return 0 on success
- @return non-zero code on failure
+ :return: 0 on success
+ :return: non-zero code on failure
"""
kind = self.dtype.kind
size = self.dtype.itemsize
@@ -198,15 +187,15 @@
overwrite=True)
def write(self, mapname, title=None, null=None, overwrite=None):
- """!Write array into raster map
+ """Write array into raster map
- @param mapname name for raster map
- @param title title for raster map
- @param null null value
- @param overwrite True for overwritting existing raster maps
+ :param str mapname: name for raster map
+ :param str title: title for raster map
+ :param null: null value
+ :param bool overwrite: True for overwritting existing raster maps
- @return 0 on success
- @return non-zero code on failure
+ :return: 0 on success
+ :return: non-zero code on failure
"""
kind = self.dtype.kind
size = self.dtype.itemsize
@@ -246,12 +235,13 @@
###############################################################################
+
class array3d(numpy.memmap):
def __new__(cls, dtype=numpy.double):
- """!Define new 3d numpy array
+ """Define new 3d numpy array
- @param cls
- @param dtype data type (default: numpy.double)
+ :param cls:
+ :param dtype: data type (default: numpy.double)
"""
reg = grass.region(True)
r = reg['rows3']
@@ -279,13 +269,13 @@
try_remove(self.filename)
def read(self, mapname, null=None):
- """!Read 3D raster map into array
+ """Read 3D raster map into array
- @param mapname name of 3D raster map to be read
- @param null null value
+ :param str mapname: name of 3D raster map to be read
+ :param null: null value
- @return 0 on success
- @return non-zero code on failure
+ :return: 0 on success
+ :return: non-zero code on failure
"""
kind = self.dtype.kind
size = self.dtype.itemsize
@@ -311,14 +301,14 @@
overwrite=True)
def write(self, mapname, null=None, overwrite=None):
- """!Write array into 3D raster map
+ """Write array into 3D raster map
- @param mapname name for 3D raster map
- @param null null value
- @param overwrite True for overwriting existing raster maps
+ :param str mapname: name for 3D raster map
+ :param null: null value
+ :param bool overwrite: True for overwriting existing raster maps
- @return 0 on success
- @return non-zero code on failure
+ :return: 0 on success
+ :return: non-zero code on failure
"""
kind = self.dtype.kind
size = self.dtype.itemsize
@@ -353,4 +343,3 @@
depths=reg['depths'],
rows=reg['rows3'],
cols=reg['cols3'])
-
Modified: grass/trunk/lib/python/script/core.py
===================================================================
--- grass/trunk/lib/python/script/core.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/core.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -1,26 +1,21 @@
-"""!@package grass.script.core
-
- at brief GRASS Python scripting module (core functions)
-
+"""
Core functions to be used in Python scripts.
Usage:
- at code
-from grass.script import core as grass
+::
-grass.parser()
-...
- at endcode
+ 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.
- at author Glynn Clements
- at author Martin Landa <landa.martin gmail.com>
- at author Michael Barton <michael.barton asu.edu>
+.. sectionauthor:: Glynn Clements
+.. sectionauthor:: Martin Landa <landa.martin gmail.com>
+.. sectionauthor:: Michael Barton <michael.barton asu.edu>
"""
import os
@@ -51,10 +46,10 @@
return arg
def __init__(self, args, **kwargs):
- if ( sys.platform == 'win32'
- and isinstance(args, list)
- and not kwargs.get('shell', False)
- and kwargs.get('executable') is None ):
+ if (sys.platform == 'win32'
+ and isinstance(args, list)
+ and not kwargs.get('shell', False)
+ and kwargs.get('executable') is None):
cmd = shutil_which(args[0])
if cmd is None:
raise OSError
@@ -94,19 +89,17 @@
def get_commands():
- """!Create list of available GRASS commands to use when parsing
+ """Create list of available GRASS commands to use when parsing
string from the command line
- @return list of commands (set) and directory of scripts (collected
- by extension - MS Windows only)
+ :return: list of commands (set) and directory of scripts (collected
+ by extension - MS Windows only)
- @code
>>> cmds = list(get_commands()[0])
>>> cmds.sort()
>>> cmds[:5]
['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate', 'd.erase']
- @endcode
"""
gisbase = os.environ['GISBASE']
cmd = list()
@@ -150,6 +143,10 @@
of os.environ.get("PATH"), or can be overridden with a custom search
path.
+ :param cmd: the command
+ :param mode:
+ :param path:
+
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
@@ -224,7 +221,7 @@
# This function also could skip the check for platform but depends
# how will be used, this is most general but not most effective.
def get_real_command(cmd):
- """!Returns the real file commad for a module (cmd)
+ """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.
@@ -233,6 +230,8 @@
>>> get_real_command('g.region')
'g.region'
+
+ :param cmd: the command
"""
if sys.platform == 'win32':
# we in fact expect pure module name (without extension)
@@ -248,23 +247,22 @@
def make_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
**options):
- """!Return a list of strings suitable for use as the args parameter to
+ """Return a list of strings suitable for use as the args parameter to
Popen() or call(). Example:
- @code
+
>>> make_command("g.message", flags = 'w', message = 'this is a warning')
['g.message', '-w', 'message=this is a warning']
- @endcode
- @param prog GRASS module
- @param flags flags to be used (given as a string)
- @param overwrite True to enable overwriting the output (<tt>--o</tt>)
- @param quiet True to run quietly (<tt>--q</tt>)
- @param verbose True to run verbosely (<tt>--v</tt>)
- @param options module's parameters
+ :param str prog: GRASS module
+ :param str flags: flags to be used (given as a string)
+ :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
+ :param bool quiet: True to run quietly (<tt>--q</tt>)
+ :param bool verbose: True to run verbosely (<tt>--v</tt>)
+ :param options: module's parameters
- @return list of arguments
+ :return: list of arguments
"""
args = [prog]
if overwrite:
@@ -287,11 +285,10 @@
def start_command(prog, flags="", overwrite=False, quiet=False,
verbose=False, **kwargs):
- """!Returns a Popen object with the command created by make_command.
+ """Returns a Popen object with the command created by make_command.
Accepts any of the arguments which Popen() accepts apart from "args"
and "shell".
- @code
>>> p = start_command("g.gisenv", stdout=subprocess.PIPE)
>>> print p # doctest: +ELLIPSIS
<...Popen object at 0x...>
@@ -303,16 +300,15 @@
GUI='text';
MONITOR='x0';
- @endcode
- @param prog GRASS module
- @param flags flags to be used (given as a string)
- @param overwrite True to enable overwriting the output (<tt>--o</tt>)
- @param quiet True to run quietly (<tt>--q</tt>)
- @param verbose True to run verbosely (<tt>--v</tt>)
- @param kwargs module's parameters
+ :param str prog: GRASS module
+ :param str flags: flags to be used (given as a string)
+ :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
+ :param bool quiet: True to run quietly (<tt>--q</tt>)
+ :param bool verbose: True to run verbosely (<tt>--v</tt>)
+ :param kwargs: module's parameters
- @return Popen object
+ :return: Popen object
"""
options = {}
popts = {}
@@ -336,24 +332,23 @@
def run_command(*args, **kwargs):
- """!Passes all arguments to start_command(), then waits for the process to
+ """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.
- @param args list of unnamed arguments (see start_command() for details)
- @param kwargs list of named arguments (see start_command() for details)
+ :param list args: list of unnamed arguments (see start_command() for details)
+ :param list kwargs: list of named arguments (see start_command() for details)
- @return exit code (0 for success)
+ :return: exit code (0 for success)
"""
ps = start_command(*args, **kwargs)
return ps.wait()
def pipe_command(*args, **kwargs):
- """!Passes all arguments to start_command(), but also adds
+ """Passes all arguments to start_command(), but also adds
"stdout = PIPE". Returns the Popen object.
- @code
>>> p = pipe_command("g.gisenv")
>>> print p # doctest: +ELLIPSIS
<....Popen object at 0x...>
@@ -365,64 +360,62 @@
GUI='text';
MONITOR='x0';
- @endcode
+ :param list args: list of unnamed arguments (see start_command() for details)
+ :param list kwargs: list of named arguments (see start_command() for details)
- @param args list of unnamed arguments (see start_command() for details)
- @param kwargs list of named arguments (see start_command() for details)
-
- @return Popen object
+ :return: Popen object
"""
kwargs['stdout'] = PIPE
return start_command(*args, **kwargs)
def feed_command(*args, **kwargs):
- """!Passes all arguments to start_command(), but also adds
+ """Passes all arguments to start_command(), but also adds
"stdin = PIPE". Returns the Popen object.
- @param args list of unnamed arguments (see start_command() for details)
- @param kwargs list of named arguments (see start_command() for details)
+ :param list args: list of unnamed arguments (see start_command() for details)
+ :param list kwargs: list of named arguments (see start_command() for details)
- @return Popen object
+ :return: Popen object
"""
kwargs['stdin'] = PIPE
return start_command(*args, **kwargs)
def read_command(*args, **kwargs):
- """!Passes all arguments to pipe_command, then waits for the process to
+ """Passes all arguments to pipe_command, then waits for the process to
complete, returning its stdout (i.e. similar to shell `backticks`).
- @param args list of unnamed arguments (see start_command() for details)
- @param kwargs list of named arguments (see start_command() for details)
+ :param list args: list of unnamed arguments (see start_command() for details)
+ :param list kwargs: list of named arguments (see start_command() for details)
- @return stdout
+ :return: stdout
"""
ps = pipe_command(*args, **kwargs)
return ps.communicate()[0]
def parse_command(*args, **kwargs):
- """!Passes all arguments to read_command, then parses the output
+ """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.
- @code
- parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
- @endcode
+ ::
+ parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
+
or you can simply define <em>delimiter</em>
- @code
- parse_command(..., delimiter = ':')
- @endcode
+ ::
- @param args list of unnamed arguments (see start_command() for details)
- @param kwargs list of named arguments (see start_command() for details)
+ parse_command(..., delimiter = ':')
- @return parsed module output
+ :param args: list of unnamed arguments (see start_command() for details)
+ :param kwargs: list of named arguments (see start_command() for details)
+
+ :return: parsed module output
"""
parse = None
parse_args = {}
@@ -445,13 +438,13 @@
def write_command(*args, **kwargs):
- """!Passes all arguments to feed_command, with the string specified
+ """Passes all arguments to feed_command, with the string specified
by the 'stdin' argument fed to the process' stdin.
- @param args list of unnamed arguments (see start_command() for details)
- @param kwargs list of named arguments (see start_command() for details)
+ :param list args: list of unnamed arguments (see start_command() for details)
+ :param list kwargs: list of named arguments (see start_command() for details)
- @return return code
+ :return: return code
"""
stdin = kwargs['stdin']
p = feed_command(*args, **kwargs)
@@ -462,20 +455,20 @@
def exec_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
env=None, **kwargs):
- """!Interface to os.execvpe(), but with the make_command() interface.
+ """Interface to os.execvpe(), but with the make_command() interface.
- @param prog GRASS module
- @param flags flags to be used (given as a string)
- @param overwrite True to enable overwriting the output (<tt>--o</tt>)
- @param quiet True to run quietly (<tt>--q</tt>)
- @param verbose True to run verbosely (<tt>--v</tt>)
- @param env directory with environmental variables
- @param kwargs module's parameters
+ :param str prog: GRASS module
+ :param str flags: flags to be used (given as a string)
+ :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
+ :param bool quiet: True to run quietly (<tt>--q</tt>)
+ :param bool verbose: True to run verbosely (<tt>--v</tt>)
+ :param env: directory with environmental variables
+ :param list kwargs: module's parameters
"""
args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
- if env == None:
+ if env is None:
env = os.environ
os.execvpe(prog, args, env)
@@ -483,19 +476,19 @@
def message(msg, flag=None):
- """!Display a message using `g.message`
+ """Display a message using `g.message`
- @param msg message to be displayed
- @param flag flags (given as string)
+ :param str msg: message to be displayed
+ :param str flag: flags (given as string)
"""
run_command("g.message", flags=flag, message=msg)
def debug(msg, debug=1):
- """!Display a debugging message using `g.message -d`
+ """Display a debugging message using `g.message -d`
- @param msg debugging message to be displayed
- @param debug debug level (0-5)
+ :param str msg: debugging message to be displayed
+ :param str debug: debug level (0-5)
"""
if debug_level() >= debug:
if sys.platform == "win32":
@@ -504,61 +497,61 @@
run_command("g.message", flags='d', message=msg, debug=debug)
def verbose(msg):
- """!Display a verbose message using `g.message -v`
+ """Display a verbose message using `g.message -v`
- @param msg verbose message to be displayed
+ :param str msg: verbose message to be displayed
"""
message(msg, flag='v')
def info(msg):
- """!Display an informational message using `g.message -i`
+ """Display an informational message using `g.message -i`
- @param msg informational message to be displayed
+ :param str msg: informational message to be displayed
"""
message(msg, flag='i')
def percent(i, n, s):
- """!Display a progress info message using `g.message -p`
+ """Display a progress info message using `g.message -p`
- @code
- message(_("Percent complete..."))
- n = 100
- for i in range(n):
- percent(i, n, 1)
- percent(1, 1, 1)
- @endcode
+ ::
- @param i current item
- @param n total number of items
- @param s increment size
+ message(_("Percent complete..."))
+ n = 100
+ for i in range(n):
+ percent(i, n, 1)
+ percent(1, 1, 1)
+
+ :param int i: current item
+ :param int n: total number of items
+ :param int s: increment size
"""
message("%d %d %d" % (i, n, s), flag='p')
def warning(msg):
- """!Display a warning message using `g.message -w`
+ """Display a warning message using `g.message -w`
- @param msg warning message to be displayed
+ :param str msg: warning message to be displayed
"""
message(msg, flag='w')
def error(msg):
- """!Display an error message using `g.message -e`
+ """Display an error message using `g.message -e`
- @param msg error message to be displayed
+ :param str msg: error message to be displayed
"""
message(msg, flag='e')
def fatal(msg):
- """!Display an error message using `g.message -e`, then abort
+ """Display an error message using `g.message -e`, then abort
Raise exception when raise_on_error is 'True'.
- @param msg error message to be displayed
+ :param str msg: error message to be displayed
"""
global raise_on_error
if raise_on_error:
@@ -569,12 +562,12 @@
def set_raise_on_error(raise_exp=True):
- """!Define behaviour on fatal error (fatal() called)
+ """Define behaviour on fatal error (fatal() called)
- @param raise_exp True to raise ScriptError instead of calling
- sys.exit(1) in fatal()
+ :param bool raise_exp: True to raise ScriptError instead of calling
+ sys.exit(1) in fatal()
- @return current status
+ :return: current status
"""
global raise_on_error
tmp_raise = raise_on_error
@@ -583,7 +576,7 @@
def get_raise_on_error():
- """!Return True if a ScriptError exception is raised instead of calling
+ """Return True if a ScriptError exception is raised instead of calling
sys.exit(1) in case a fatal error was invoked with fatal()
"""
global raise_on_error
@@ -616,13 +609,13 @@
def parser():
- """!Interface to g.parser, intended to be run from the top-level, e.g.:
+ """Interface to g.parser, intended to be run from the top-level, e.g.:
- @code
+ ::
+
if __name__ == "__main__":
options, flags = grass.parser()
main()
- @endcode
Thereafter, the global variables "options" and "flags" will be
dictionaries containing option/flag values, keyed by lower-case
@@ -660,12 +653,11 @@
def tempfile(create=True):
- """!Returns the name of a temporary file, created with
- g.tempfile.
+ """Returns the name of a temporary file, created with g.tempfile.
- @param create True to create a file
+ :param bool create: True to create a file
- @return path to a tmp file
+ :return: path to a tmp file
"""
flags = ''
if not create:
@@ -675,7 +667,7 @@
def tempdir():
- """!Returns the name of a temporary dir, created with g.tempfile."""
+ """Returns the name of a temporary dir, created with g.tempfile."""
tmp = tempfile(create=False)
os.mkdir(tmp)
@@ -683,14 +675,13 @@
def _compare_projection(dic):
- """
- !Check if projection has some possibility of duplicate names like
- Universal Transverse Mercator and Universe Transverse Mercator and
- unify them
+ """Check if projection has some possibility of duplicate names like
+ Universal Transverse Mercator and Universe Transverse Mercator and
+ unify them
- @param dic The dictionary containing information about projection
+ :param dic: The dictionary containing information about projection
- @return The dictionary with the new values if needed
+ :return: The dictionary with the new values if needed
"""
# the lookup variable is a list of list, each list contains all the
@@ -704,13 +695,12 @@
def _compare_units(dic):
- """
- !Check if units has some possibility of duplicate names like
- meter and metre and unify them
+ """Check if units has some possibility of duplicate names like
+ meter and metre and unify them
- @param dic The dictionary containing information about units
+ :param dic: The dictionary containing information about units
- @return The dictionary with the new values if needed
+ :return: The dictionary with the new values if needed
"""
# the lookup variable is a list of list, each list contains all the
@@ -729,32 +719,34 @@
def _text_to_key_value_dict(filename, sep=":", val_sep=",", checkproj=False,
checkunits=False):
- """
- !Convert a key-value text file, where entries are separated
- by newlines and the key and value are separated by `sep',
- into a key-value dictionary and discover/use the correct
- data types (float, int or string) for values.
+ """Convert a key-value text file, where entries are separated by newlines
+ and the key and value are separated by `sep', into a key-value dictionary
+ and discover/use the correct data types (float, int or string) for values.
- @param filename The name or name and path of the text file to convert
- @param sep The character that separates the keys and values, default is ":"
- @param val_sep The character that separates the values of a single key, default is ","
- @param checkproj True if it has to check some information about projection system
- @param checkproj True if it has to check some information about units
+ :param str filename: The name or name and path of the text file to convert
+ :param str sep: The character that separates the keys and values, default
+ is ":"
+ :param str val_sep: The character that separates the values of a single
+ key, default is ","
+ :param bool checkproj: True if it has to check some information about
+ projection system
+ :param bool checkproj: True if it has to check some information about units
- @return The dictionary
+ :return: The dictionary
- A text file with this content:
- \code
+ A text file with this content:
+ ::
+
a: Hello
b: 1.0
c: 1,2,3,4,5
d : hello,8,0.1
- \endcode
- Will be represented as this dictionary:
- \code
+ Will be represented as this dictionary:
+
+ ::
+
{'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
- \endcode
"""
text = open(filename, "r").readlines()
@@ -803,8 +795,7 @@
def compare_key_value_text_files(filename_a, filename_b, sep=":",
val_sep=",", precision=0.000001,
proj=False, units=False):
- """
- !Compare two key-value text files
+ """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.
@@ -812,22 +803,23 @@
(float, int or string) to allow correct comparison.
An example key-value text file may have this content:
- \code
- a: Hello
- b: 1.0
- c: 1,2,3,4,5
- d : hello,8,0.1
- \endcode
- @param filename_a name of the first key-value text file
- @param filenmae_b name of the second key-value text file
- @param sep character that separates the keys and values, default is ":"
- @param val_sep character that separates the values of a single key, default is ","
- @param precision precision with which the floating point values are compared
- @param proj True if it has to check some information about projection system
- @param units True if it has to check some information about units
+ ::
- @return True if full or almost identical, False if different
+ a: Hello
+ b: 1.0
+ c: 1,2,3,4,5
+ d : hello,8,0.1
+
+ :param str filename_a: name of the first key-value text file
+ :param str filenmae_b: name of the second key-value text file
+ :param str sep: character that separates the keys and values, default is ":"
+ :param str val_sep: character that separates the values of a single key, default is ","
+ :param double precision: precision with which the floating point values are compared
+ :param bool proj: True if it has to check some information about projection system
+ :param bool units: True if it has to check some information about units
+
+ :return: True if full or almost identical, False if different
"""
dict_a = _text_to_key_value_dict(filename_a, sep, checkproj=proj,
checkunits=units)
@@ -860,17 +852,14 @@
def gisenv():
- """!Returns the output from running g.gisenv (with no arguments), as a
+ """Returns the output from running g.gisenv (with no arguments), as a
dictionary. Example:
- @code
>>> env = gisenv()
>>> print env['GISDBASE'] # doctest: +SKIP
/opt/grass-data
- @endcode
-
- @return list of GRASS variables
+ :return: list of GRASS variables
"""
s = read_command("g.gisenv", flags='n')
return parse_key_val(s)
@@ -879,10 +868,10 @@
def locn_is_latlong():
- """!Tests if location is lat/long. Value is obtained
+ """Tests if location is lat/long. Value is obtained
by checking the "g.region -pu" projection code.
- @return True for a lat/long region, False otherwise
+ :return: True for a lat/long region, False otherwise
"""
s = read_command("g.region", flags='pu')
kv = parse_key_val(s, ':')
@@ -893,12 +882,12 @@
def region(region3d=False, complete=False):
- """!Returns the output from running "g.region -gu", as a
+ """Returns the output from running "g.region -gu", as a
dictionary. Example:
- @param region3d True to get 3D region
+ :param bool region3d: True to get 3D region
+ :param bool complete:
- @code
>>> curent_region = region()
>>> # obtain n, s, e and w values
>>> [curent_region[key] for key in "nsew"] # doctest: +ELLIPSIS
@@ -907,9 +896,7 @@
>>> (curent_region['nsres'], curent_region['ewres']) # doctest: +ELLIPSIS
(..., ...)
- @endcode
-
- @return dictionary of region values
+ :return: dictionary of region values
"""
flgs = 'gu'
if region3d:
@@ -929,7 +916,7 @@
def region_env(region3d=False, **kwargs):
- """!Returns region settings as a string which can used as
+ """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
@@ -938,16 +925,17 @@
See also use_temp_region() for alternative method how to define
temporary region used for raster-based computation.
- \param region3d True to get 3D region
- \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
- \code
- os.environ['GRASS_REGION'] = grass.region_env(region='detail')
- grass.mapcalc('map=1', overwrite=True)
- os.environ.pop('GRASS_REGION')
- \endcode
+ :param bool region3d: True to get 3D region
+ :param kwargs: g.region's parameters like 'rast', 'vect' or 'region'
- @return string with region values
- @return empty string on error
+ ::
+
+ os.environ['GRASS_REGION'] = grass.region_env(region='detail')
+ grass.mapcalc('map=1', overwrite=True)
+ os.environ.pop('GRASS_REGION')
+
+ :return: string with region values
+ :return: empty string on error
"""
# read proj/zone from WIND file
env = gisenv()
@@ -1004,7 +992,7 @@
def use_temp_region():
- """!Copies the current region to a temporary region with "g.region save=",
+ """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.
"""
@@ -1015,7 +1003,7 @@
def del_temp_region():
- """!Unsets WIND_OVERRIDE and removes any region named by it."""
+ """Unsets WIND_OVERRIDE and removes any region named by it."""
try:
name = os.environ.pop('WIND_OVERRIDE')
run_command("g.remove", quiet=True, region=name)
@@ -1026,23 +1014,21 @@
def find_file(name, element='cell', mapset=None):
- """!Returns the output from running g.findfile as a
+ """Returns the output from running g.findfile as a
dictionary. Example:
- @code
>>> result = find_file('elevation', element='cell')
>>> print result['fullname']
elevation at PERMANENT
>>> print result['file'] # doctest: +ELLIPSIS
/.../PERMANENT/cell/elevation
- @endcode
- @param name file name
- @param element element type (default 'cell')
- @param mapset mapset name (default all mapsets in search path)
+ :param str name: file name
+ :param str element: element type (default 'cell')
+ :param str mapset: mapset name (default all mapsets in search path)
- @return parsed output of g.findfile
+ :return: parsed output of g.findfile
"""
if element == 'raster' or element == 'rast':
verbose(_('Element type should be "cell" and not "%s"') % element)
@@ -1055,23 +1041,21 @@
def list_grouped(type, check_search_path=True):
- """!List elements grouped by mapsets.
+ """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:
- @code
- >>> list_grouped('rast')['PERMANENT'] # doctest: +ELLIPSIS
- [..., 'lakes', ..., 'slope', ...
+ >>> list_grouped('rast')['PERMANENT'] # doctest: +ELLIPSIS
+ ['basins' ... 'landuse']
- @endcode
- @param type element type (rast, vect, rast3d, region, ...)
- @param check_search_path True to add mapsets for the search path with no
- found elements
+ :param str type: element type (rast, vect, rast3d, region, ...)
+ :param bool check_search_path: True to add mapsets for the search path
+ with no found elements
- @return directory of mapsets/elements
+ :return: directory of mapsets/elements
"""
if type == 'raster' or type == 'cell':
verbose(_('Element type should be "rast" and not "%s"') % type)
@@ -1109,40 +1093,34 @@
def list_pairs(type):
- """!List of elements as tuples.
+ """List of elements as tuples.
Returns the output from running g.list, as a list of (map, mapset)
pairs. Example:
- @code
- >>> list_pairs('rast') # doctest: +ELLIPSIS
- [..., ('lakes', 'PERMANENT'), ..., ('slope', 'PERMANENT'), ...
+ >>> list_pairs('rast') # doctest: +ELLIPSIS
+ [('basins', 'PERMANENT'), ... ('landuse', 'PERMANENT')]
- @endcode
+ :param str type: element type (rast, vect, rast3d, region, ...)
- @param type element type (rast, vect, rast3d, region, ...)
-
- @return list of tuples (map, mapset)
+ :return: list of tuples (map, mapset)
"""
return _concat([[(map, mapset) for map in maps]
for mapset, maps in list_grouped(type).iteritems()])
def list_strings(type):
- """!List of elements as strings.
+ """List of elements as strings.
Returns the output from running g.list, as a list of qualified
names. Example:
- @code
>>> list_strings('rast') # doctest: +ELLIPSIS
[..., 'lakes at PERMANENT', ..., 'slope at PERMANENT', ...
- @endcode
+ :param str type: element type
- @param type element type
-
- @return list of strings ('map@@mapset')
+ :return: list of strings ('map@@mapset')
"""
return ["%s@%s" % pair for pair in list_pairs(type)]
@@ -1150,19 +1128,19 @@
def mlist_strings(type, pattern=None, mapset=None, exclude=None, flag=''):
- """!List of elements as strings.
+ """List of elements as strings.
Returns the output from running g.mlist, as a list of qualified
names.
- @param type element type (rast, vect, rast3d, region, ...)
- @param pattern pattern string
- @param mapset mapset name (if not given use search path)
- @param exclude pattern string to exclude maps from the research
- @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
- (glob pattern)
+ :param str type: element type (rast, vect, rast3d, region, ...)
+ :param str pattern: pattern string
+ :param str mapset: mapset name (if not given use search path)
+ :param str exclude: pattern string to exclude maps from the research
+ :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
+ or '' (glob pattern)
- @return list of elements
+ :return: list of elements
"""
if type == 'raster' or type == 'cell':
verbose(_('Element type should be "rast" and not "%s"') % type)
@@ -1181,19 +1159,19 @@
def mlist_pairs(type, pattern=None, mapset=None, exclude=None, flag=''):
- """!List of elements as pairs
+ """List of elements as pairs
Returns the output from running g.mlist, as a list of
(name, mapset) pairs
- @param type element type (rast, vect, rast3d, region, ...)
- @param pattern pattern string
- @param mapset mapset name (if not given use search path)
- @param exclude pattern string to exclude maps from the research
- @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
- (glob pattern)
+ :param str type: element type (rast, vect, rast3d, region, ...)
+ :param str pattern: pattern string
+ :param str mapset: mapset name (if not given use search path)
+ :param str exclude: pattern string to exclude maps from the research
+ :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
+ or '' (glob pattern)
- @return list of elements
+ :return: list of elements
"""
return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern,
mapset, exclude,
@@ -1202,27 +1180,24 @@
def mlist_grouped(type, pattern=None, check_search_path=True, exclude=None,
flag=''):
- """!List of elements grouped by mapsets.
+ """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:
- @code
>>> mlist_grouped('vect', pattern='*roads*')['PERMANENT']
['railroads', 'roadsmajor']
- @endcode
+ :param str type: element type (rast, vect, rast3d, region, ...)
+ :param str pattern: pattern string
+ :param str check_search_path: True to add mapsets for the search path
+ with no found elements
+ :param str exclude: pattern string to exclude maps from the research
+ :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
+ or '' (glob pattern)
- @param type element type (rast, vect, rast3d, region, ...)
- @param pattern pattern string
- @param check_search_path True to add mapsets for the search path with no
- found elements
- @param exclude pattern string to exclude maps from the research
- @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
- (glob pattern)
-
- @return directory of mapsets/elements
+ :return: directory of mapsets/elements
"""
if type == 'raster' or type == 'cell':
verbose(_('Element type should be "rast" and not "%s"') % type)
@@ -1270,23 +1245,20 @@
def parse_color(val, dflt=None):
- """!Parses the string "val" as a GRASS colour, which can be either one of
+ """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:
- @code
>>> parse_color("red")
(1.0, 0.0, 0.0)
>>> parse_color("255:0:0")
(1.0, 0.0, 0.0)
- @endcode
+ :param val: color value
+ :param dflt: default color value
- @param val color value
- @param dflt default color value
-
- @return tuple RGB
+ :return: tuple RGB
"""
if val in named_colors:
return named_colors[val]
@@ -1301,7 +1273,7 @@
def overwrite():
- """!Return True if existing files may be overwritten"""
+ """Return True if existing files may be overwritten"""
owstr = 'GRASS_OVERWRITE'
return owstr in os.environ and os.environ[owstr] != '0'
@@ -1309,7 +1281,7 @@
def verbosity():
- """!Return the verbosity level selected by GRASS_VERBOSE"""
+ """Return the verbosity level selected by GRASS_VERBOSE"""
vbstr = os.getenv('GRASS_VERBOSE')
if vbstr:
return int(vbstr)
@@ -1319,7 +1291,7 @@
## various utilities, not specific to GRASS
def find_program(pgm, *args):
- """!Attempt to run a program, with optional arguments.
+ """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
@@ -1328,20 +1300,17 @@
Example:
- @code
>>> find_program('r.sun', '--help')
True
>>> find_program('ls', '--version')
True
- @endcode
+ :param str pgm: program name
+ :param args: list of arguments
- @param pgm program name
- @param args list of arguments
-
- @return False if the attempt failed due to a missing executable
+ :return: False if the attempt failed due to a missing executable
or non-zero return code
- @return True otherwise
+ :return: True otherwise
"""
nuldev = file(os.devnull, 'w+')
try:
@@ -1358,11 +1327,11 @@
def mapsets(search_path=False):
- """!List available mapsets
+ """List available mapsets
- @param search_path True to list mapsets only in search path
+ :param bool search_path: True to list mapsets only in search path
- @return list of mapsets
+ :return: list of mapsets
"""
if search_path:
flags = 'p'
@@ -1381,21 +1350,24 @@
def create_location(dbase, location, epsg=None, proj4=None, filename=None,
- wkt=None, datum=None, datum_trans=None, desc=None, overwrite=False):
- """!Create new location
+ wkt=None, datum=None, datum_trans=None, desc=None,
+ overwrite=False):
+ """Create new location
Raise ScriptError on error.
- @param dbase path to GRASS database
- @param location location name to create
- @param epsg if given create new location based on EPSG code
- @param proj4 if given create new location based on Proj4 definition
- @param filename if given create new location based on georeferenced file
- @param wkt if given create new location based on WKT definition (path to PRJ file)
- @param datum GRASS format datum code
- @param datum_trans datum transformation parameters (used for epsg and proj4)
- @param desc description of the location (creates MYNAME file)
- @param overwrite True to overwrite location if exists (WARNING: ALL DATA from existing location ARE DELETED!)
+ :param str dbase: path to GRASS database
+ :param str location: location name to create
+ :param epsg: if given create new location based on EPSG code
+ :param proj4: if given create new location based on Proj4 definition
+ :param str filename: if given create new location based on georeferenced file
+ :param str wkt: if given create new location based on WKT definition
+ (path to PRJ file)
+ :param datum: GRASS format datum code
+ :param datum_trans: datum transformation parameters (used for epsg and proj4)
+ :param desc: description of the location (creates MYNAME file)
+ :param bool overwrite: True to overwrite location if exists(WARNING:
+ ALL DATA from existing location ARE DELETED!)
"""
gisdbase = None
if epsg or proj4 or filename or wkt:
@@ -1456,12 +1428,12 @@
def _create_location_xy(database, location):
- """!Create unprojected location
+ """Create unprojected location
Raise ScriptError on error.
- @param database GRASS database where to create new location
- @param location location name
+ :param database: GRASS database where to create new location
+ :param location: location name
"""
cur_dir = os.getcwd()
try:
@@ -1506,16 +1478,17 @@
def version():
- """!Get GRASS version as dictionary
+ """Get GRASS version as dictionary
- @code
- 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'}
- @endcode
+ 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'}
+
"""
data = parse_command('g.version', flags='rge')
for k, v in data.iteritems():
@@ -1538,11 +1511,13 @@
def legal_name(s):
- """!Checks if the string contains only allowed characters.
+ """Checks if the string contains only allowed characters.
This is the Python implementation of G_legal_filename() function.
- @note It is not clear when to use this function.
+ ..note::
+
+ It is not clear when to use this function.
"""
if not s or s[0] == '.':
warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with " \
Modified: grass/trunk/lib/python/script/db.py
===================================================================
--- grass/trunk/lib/python/script/db.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/db.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -18,8 +18,8 @@
License (>=v2). Read the file COPYING that comes with GRASS
for details.
- at author Glynn Clements
- at author Martin Landa <landa.martin gmail.com>
+.. sectionauthor:: Glynn Clements
+.. sectionauthor:: Martin Landa <landa.martin gmail.com>
"""
from core import *
@@ -30,8 +30,12 @@
"""Return the list of columns for a database table
(interface to `db.describe -c'). Example:
- >>> db_describe('firestations') # doctest: +ELLIPSIS
+ >>> run_command('g.copy', vect='firestations,myfirestations')
+ 0
+ >>> db_describe('myfirestations') # doctest: +ELLIPSIS
{'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22}
+ >>> run_command('g.remove', vect='myfirestations')
+ 0
:param str table: table name
:param list args:
@@ -66,8 +70,12 @@
If no driver or database are given, then default settings is used
(check db_connection()).
- >>> db_table_exist('firestations')
+ >>> run_command('g.copy', vect='firestations,myfirestations')
+ 0
+ >>> db_table_exist('myfirestations')
True
+ >>> run_command('g.remove', vect='myfirestations')
+ 0
:param str table: table name
:param args:
@@ -104,12 +112,17 @@
Examples:
- >>> db_select(sql = 'SELECT cat,CITY FROM firestations WHERE cat < 4')
- (('1', 'Vet School'), ('2', 'West'), ('3', 'North'))
+ >>> run_command('g.copy', vect='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 busstopsall</tt>.)
+ Simplyfied usage (it performs <tt>SELECT * FROM myfirestations</tt>.)
- >>> db_select(table = 'firestations')
+ >>> db_select(table = 'myfirestations') # doctest: +ELLIPSIS
+ (('1', '24', 'Morrisville #3', ... 'HS2A', '1.37'))
+ >>> run_command('g.remove', vect='myfirestations')
+ 0
:param str sql: SQL statement to perform (or None)
:param str filename: name of file with SQL statements (or None)
@@ -149,14 +162,15 @@
"""Return the name of vector connected to the table.
It returns None if no vectors are connected to the table.
- >>> db_table_in_vector('geology')
- ['geology at PERMANENT']
- >>> db_table_in_vector('geologies')
+ >>> run_command('g.copy', vect='firestations,myfirestations')
+ 0
+ >>> db_table_in_vector('myfirestations')
+ ['myfirestations at user1']
+ >>> db_table_in_vector('mfirestations')
+ >>> run_command('g.remove', vect='myfirestations')
+ 0
-
:param str table: name of table to query
-
-
"""
from vector import vector_db
nuldev = file(os.devnull, 'w')
Modified: grass/trunk/lib/python/script/raster.py
===================================================================
--- grass/trunk/lib/python/script/raster.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/raster.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -1,4 +1,4 @@
-"""!@package grass.script.raster
+"""@package grass.script.raster
@brief GRASS Python scripting module (raster functions)
@@ -6,20 +6,19 @@
Usage:
- at code
-from grass.script import raster as grass
+::
-grass.raster_history(map)
-...
- at endcode
+ 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.
- at author Glynn Clements
- at author Martin Landa <landa.martin gmail.com>
+.. sectionauthor:: Glynn Clements
+.. sectionauthor:: Martin Landa <landa.martin gmail.com>
"""
import os
@@ -30,44 +29,38 @@
from core import *
from utils import float_or_dms, parse_key_val
-# add raster history
def raster_history(map):
- """!Set the command history for a raster map to the command used to
+ """Set the command history for a raster map to the command used to
invoke the script (interface to `r.support').
- @param map map name
+ :param str map: map name
- @return True on success
- @return False on failure
+ :return: True on success
+ :return: False on failure
+
"""
current_mapset = gisenv()['MAPSET']
- if find_file(name = map)['mapset'] == current_mapset:
- run_command('r.support', map = map, history = os.environ['CMDLINE'])
+ if find_file(name=map)['mapset'] == current_mapset:
+ run_command('r.support', map=map, history=os.environ['CMDLINE'])
return True
-
+
warning(_("Unable to write history for <%(map)s>. "
- "Raster map <%(map)s> not found in current mapset." % { 'map' : map, 'map' : map}))
+ "Raster map <%(map)s> not found in current mapset." % { 'map': map, 'map': map}))
return False
-# run "r.info -gre ..." and parse output
def raster_info(map):
- """!Return information about a raster map (interface to
- `r.info'). Example:
+ """Return information about a raster map (interface to
+ `r.info -gre'). Example:
- \code
- >>> grass.raster_info('elevation')
- {'north': 228500.0, 'timestamp': '"none"', 'min': 55.578792572021499,
- 'datatype': 'FCELL', 'max': 156.32986450195301, 'ewres': 10.0,
- 'vertical_datum': '', 'west': 630000.0, 'units': '',
- 'title': 'South-West Wake county: Elevation NED 10m (elev_ned10m)',
- 'east': 645000.0, 'nsres': 10.0, 'south': 215000.0}
- \endcode
+ >>> raster_info('elevation') # doctest: +ELLIPSIS
+ {'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}
- @param map map name
-
- @return parsed raster info
+ :param str map: map name
+
+ :return: parsed raster info
+
"""
def float_or_null(s):
@@ -76,7 +69,7 @@
else:
return float(s)
- s = read_command('r.info', flags = 'gre', map = map)
+ s = read_command('r.info', flags='gre', map=map)
kv = parse_key_val(s)
for k in ['min', 'max']:
kv[k] = float_or_null(kv[k])
@@ -86,20 +79,19 @@
kv[k] = float_or_dms(kv[k])
return kv
-# interface to r.mapcalc
-def mapcalc(exp, quiet = False, verbose = False, overwrite = False,
- seed = None, env = None, **kwargs):
- """!Interface to r.mapcalc.
+def mapcalc(exp, quiet=False, verbose=False, overwrite=False,
+ seed=None, env=None, **kwargs):
+ """Interface to r.mapcalc.
- @param exp expression
- @param quiet True to run quietly (<tt>--q</tt>)
- @param verbose True to run verbosely (<tt>--v</tt>)
- @param overwrite True to enable overwriting the output (<tt>--o</tt>)
- @param seed an integer used to seed the random-number generator for the rand() function,
- or 'auto' to generate a random seed
- @param env dictionary of environment variables for child process
- @param kwargs
+ :param str exp: expression
+ :param bool quiet: True to run quietly (<tt>--q</tt>)
+ :param bool verbose: True to run verbosely (<tt>--v</tt>)
+ :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
+ :param seed: an integer used to seed the random-number generator for the
+ rand() function, or 'auto' to generate a random seed
+ :param dict env: dictionary of environment variables for child process
+ :param kwargs:
"""
if seed == 'auto':
@@ -108,41 +100,40 @@
t = string.Template(exp)
e = t.substitute(**kwargs)
- if write_command('r.mapcalc', file = '-', stdin = e,
- env = env,
- seed = seed,
- quiet = quiet,
- verbose = verbose,
- overwrite = overwrite) != 0:
+ if write_command('r.mapcalc', file='-', stdin=e, env=env, seed=seed,
+ quiet=quiet, verbose=verbose, overwrite=overwrite) != 0:
fatal(_("An error occurred while running r.mapcalc"))
-def mapcalc_start(exp, quiet = False, verbose = False, overwrite = False,
- seed = None, env = None, **kwargs):
- """!Interface to r.mapcalc, doesn't wait for it to finish, returns Popen object.
+def mapcalc_start(exp, quiet=False, verbose=False, overwrite=False,
+ seed=None, env=None, **kwargs):
+ """Interface to r.mapcalc, doesn't wait for it to finish, returns Popen object.
- \code
+ >>> output = 'newele'
+ >>> input = 'elevation'
>>> expr1 = '"%s" = "%s" * 10' % (output, input)
>>> expr2 = '...' # etc.
>>> # launch the jobs:
- >>> p1 = grass.mapcalc_start(expr1)
- >>> p2 = grass.mapcalc_start(expr2) # etc.
+ >>> p1 = mapcalc_start(expr1)
+ >>> p2 = mapcalc_start(expr2)
...
>>> # wait for them to finish:
>>> p1.wait()
- >>> p2.wait() # etc.
- \endcode
+ 0
+ >>> p2.wait()
+ 1
+ >>> run_command('g.remove', rast=output)
- @param exp expression
- @param quiet True to run quietly (<tt>--q</tt>)
- @param verbose True to run verbosely (<tt>--v</tt>)
- @param overwrite True to enable overwriting the output (<tt>--o</tt>)
- @param seed an integer used to seed the random-number generator for the rand() function,
- or 'auto' to generate a random seed
- @param env dictionary of environment variables for child process
- @param kwargs
-
- @return Popen object
+ :param str exp: expression
+ :param bool quiet: True to run quietly (<tt>--q</tt>)
+ :param bool verbose: True to run verbosely (<tt>--v</tt>)
+ :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
+ :param seed: an integer used to seed the random-number generator for the
+ rand() function, or 'auto' to generate a random seed
+ :param dict env: dictionary of environment variables for child process
+ :param kwargs:
+
+ :return: Popen object
"""
if seed == 'auto':
@@ -151,19 +142,24 @@
t = string.Template(exp)
e = t.substitute(**kwargs)
- p = feed_command('r.mapcalc', file = '-',
- env = env,
- seed = seed,
- quiet = quiet,
- verbose = verbose,
- overwrite = overwrite)
+ p = feed_command('r.mapcalc', file='-', env=env, seed=seed,
+ quiet=quiet, verbose=verbose, overwrite=overwrite)
p.stdin.write(e)
p.stdin.close()
return p
-# interface to r.what
-def raster_what(map, coord, env = None):
- """!TODO"""
+
+def raster_what(map, coord, env=None):
+ """Interface to r.what
+
+ >>> raster_what('elevation', [[640000, 228000]])
+ [{'elevation': {'color': '255:214:000', 'label': '', 'value': '102.479'}}]
+
+ :param str map: the map name
+ :param list coord: a list of list containing all the point that you want
+ query
+ :param env:
+ """
if type(map) in (types.StringType, types.UnicodeType):
map_list = [map]
else:
@@ -175,18 +171,18 @@
else:
for e, n in coord:
coord_list.append('%f,%f' % (e, n))
-
+
sep = '|'
# separator '|' not included in command
# because | is causing problems on Windows
# change separator?
ret = read_command('r.what',
- flags = 'rf',
- map = ','.join(map_list),
- coordinates = ','.join(coord_list),
- null = _("No data"),
- quiet = True,
- env = env)
+ flags='rf',
+ map=','.join(map_list),
+ coordinates=','.join(coord_list),
+ null=_("No data"),
+ quiet=True,
+ env=env)
data = list()
if not ret:
return data
Modified: grass/trunk/lib/python/script/raster3d.py
===================================================================
--- grass/trunk/lib/python/script/raster3d.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/raster3d.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -1,52 +1,43 @@
-"""!@package grass.script.raster3d
-
- at brief GRASS Python scripting module (raster3d functions)
-
+"""
Raster3d related functions to be used in Python scripts.
Usage:
- at code
-from grass.script import raster3d as grass
+::
-grass.raster3d_info(map)
-...
- at endcode
+ 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.
- at author Glynn Clements
- at author Martin Landa <landa.martin gmail.com>
- at author Soeren Gebbert <soeren.gebbert gmail.com>
+.. sectionauthor:: Glynn Clements
+.. sectionauthor:: Martin Landa <landa.martin gmail.com>
+.. sectionauthor:: Soeren Gebbert <soeren.gebbert gmail.com>
"""
-import os
import string
from core import *
from utils import float_or_dms, parse_key_val
-# add raster history
-# run "r3.info -rstgip ..." and parse output
-
def raster3d_info(map):
- """!Return information about a raster3d map (interface to
- `r3.info'). Example:
+ """Return information about a raster3d map (interface to `r3.info`).
+ Example:
- \code
- >>> grass.raster3d_info('volume')
- {'tiledimz': 1, 'tbres': 1.0, 'tiledimx': 27, 'tiledimy': 16, 'north': 60.490001999999997, 'tilenumy': 1, 'tilenumz': 1,
- 'min': 1.0, 'datatype': '"DCELL"', 'max': 1.0, 'top': 0.5, 'bottom': -0.5, 'west': -3.2200000000000002, 'tilenumx': 1,
- 'ewres': 0.98222219, 'east': 23.299999, 'nsres': 0.99937511999999995, 'Timestamp': '"none"', 'south': 44.5}
- \endcode
+ >>> mapcalc3d('volume = row() + col() + depth()')
+ >>> raster3d_info('volume') # doctest: +ELLIPSIS
+ {'vertical_units': '"units"', 'tbres': 1.0, ... 'south': 185000.0}
+ >>> run_command('g.remove', rast3d='volume')
+ 0
- @param map map name
-
- @return parsed raster3d info
+ :param str map: map name
+
+ :return: parsed raster3d info
"""
def float_or_null(s):
@@ -71,22 +62,21 @@
kv[k] = int(kv[k])
return kv
-# interface to r3.mapcalc
-def mapcalc3d(exp, quiet = False, verbose = False, overwrite = False, **kwargs):
- """!Interface to r3.mapcalc.
+def mapcalc3d(exp, quiet=False, verbose=False, overwrite=False, **kwargs):
+ """Interface to r3.mapcalc.
- @param exp expression
- @param quiet True to run quietly (<tt>--q</tt>)
- @param verbose True to run verbosely (<tt>--v</tt>)
- @param overwrite True to enable overwriting the output (<tt>--o</tt>)
- @param kwargs
+ :param str exp: expression
+ :param bool quiet: True to run quietly (<tt>--q</tt>)
+ :param bool verbose: True to run verbosely (<tt>--v</tt>)
+ :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
+ :param kwargs:
"""
t = string.Template(exp)
e = t.substitute(**kwargs)
- if run_command('r3.mapcalc', expression = e,
- quiet = quiet,
- verbose = verbose,
- overwrite = overwrite) != 0:
+ if run_command('r3.mapcalc', expression=e,
+ quiet=quiet,
+ verbose=verbose,
+ overwrite=overwrite) != 0:
fatal(_("An error occurred while running r3.mapcalc"))
Modified: grass/trunk/lib/python/script/task.py
===================================================================
--- grass/trunk/lib/python/script/task.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/task.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -1,26 +1,21 @@
-"""!@package grass.script.task
-
- at brief GRASS Python scripting module (task)
-
+"""
Get interface description of GRASS commands
Based on gui/wxpython/gui_modules/menuform.py
Usage:
- at code
-from grass.script import task as gtask
+::
-gtask.command_info('r.info')
-...
- at endcode
+ 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.
- at author Martin Landa <landa.martin gmail.com>
+.. sectionauthor:: Martin Landa <landa.martin gmail.com>
"""
import types
@@ -33,22 +28,23 @@
from utils import decode
from core import *
+
class grassTask:
- """!This class holds the structures needed for filling by the
+ """This class holds the structures needed for filling by the
parser
Parameter blackList is a dictionary with fixed structure, eg.
- @code
- blackList = {'items' : {'d.legend' : { 'flags' : ['m'],
- 'params' : [] }},
+ ::
+
+ blackList = {'items' : {'d.legend' : { 'flags' : ['m'], 'params' : [] }},
'enabled': True}
- @endcode
-
- @param path full path
- @param blackList hide some options in the GUI (dictionary)
+
+
+ :param str path: full path
+ :param blackList: hide some options in the GUI (dictionary)
"""
- def __init__(self, path = None, blackList = None):
+ def __init__(self, path=None, blackList=None):
self.path = path
self.name = _('unknown')
self.params = list()
@@ -61,34 +57,34 @@
if blackList:
self.blackList = blackList
else:
- self.blackList = { 'enabled' : False, 'items' : {} }
-
+ self.blackList = {'enabled': False, 'items': {}}
+
if path is not None:
try:
- processTask(tree = etree.fromstring(get_interface_description(path)),
- task = self)
+ processTask(tree=etree.fromstring(get_interface_description(path)),
+ task=self)
except ScriptError as e:
self.errorMsg = e.value
-
+
self.define_first()
-
+
def define_first(self):
- """!Define first parameter
+ """Define first parameter
- @return name of first parameter
+ :return: name of first parameter
"""
if len(self.params) > 0:
self.firstParam = self.params[0]['name']
-
+
return self.firstParam
-
+
def get_error_msg(self):
- """!Get error message ('' for no error)
+ """Get error message ('' for no error)
"""
return self.errorMsg
-
+
def get_name(self):
- """!Get task name
+ """Get task name
"""
if sys.platform == 'win32':
name, ext = os.path.splitext(self.name)
@@ -96,13 +92,13 @@
return name
else:
return self.name
-
+
return self.name
- def get_description(self, full = True):
- """!Get module's description
+ def get_description(self, full=True):
+ """Get module's description
- @param full True for label + desc
+ :param bool full: True for label + desc
"""
if self.label:
if full:
@@ -113,38 +109,38 @@
return self.description
def get_keywords(self):
- """!Get module's keywords
+ """Get module's keywords
"""
return self.keywords
-
- def get_list_params(self, element = 'name'):
- """!Get list of parameters
- @param element element name
+ def get_list_params(self, element='name'):
+ """Get list of parameters
+
+ :param str element: element name
"""
params = []
for p in self.params:
params.append(p[element])
-
+
return params
- def get_list_flags(self, element = 'name'):
- """!Get list of flags
+ def get_list_flags(self, element='name'):
+ """Get list of flags
- @param element element name
+ :param str element: element name
"""
flags = []
for p in self.flags:
flags.append(p[element])
-
+
return flags
-
- def get_param(self, value, element = 'name', raiseError = True):
- """!Find and return a param by name
- @param value param's value
- @param element element name
- @param raiseError True for raise on error
+ def get_param(self, value, element='name', raiseError=True):
+ """Find and return a param by name
+
+ :param value: param's value
+ :param str element: element name
+ :param bool raiseError: True for raise on error
"""
try:
for p in self.params:
@@ -162,7 +158,7 @@
return p
except KeyError:
pass
-
+
if raiseError:
raise ValueError, _("Parameter element '%(element)s' not found: '%(value)s'") % \
{ 'element' : element, 'value' : value }
@@ -170,28 +166,28 @@
return None
def get_flag(self, aFlag):
- """!Find and return a flag by name
+ """Find and return a flag by name
Raises ValueError when the flag is not found.
- @param aFlag name of the flag
+ :param str aFlag: name of the flag
"""
for f in self.flags:
- if f['name'] == aFlag:
+ if f['name'] == aFlag:
return f
raise ValueError, _("Flag not found: %s") % aFlag
def get_cmd_error(self):
- """!Get error string produced by get_cmd(ignoreErrors = False)
-
- @return list of errors
+ """Get error string produced by get_cmd(ignoreErrors = False)
+
+ :return: list of errors
"""
errorList = list()
# determine if suppress_required flag is given
for f in self.flags:
if f['value'] and f['suppress_required']:
return errorList
-
+
for p in self.params:
if not p.get('value', '') and p.get('required', False):
if not p.get('default', ''):
@@ -199,136 +195,138 @@
if not desc:
desc = p['description']
errorList.append(_("Parameter '%(name)s' (%(desc)s) is missing.") % \
- {'name' : p['name'], 'desc' : desc })
-
+ {'name': p['name'], 'desc': desc})
+
return errorList
-
- def get_cmd(self, ignoreErrors = False, ignoreRequired = False, ignoreDefault = True):
- """!Produce an array of command name and arguments for feeding
+
+ def get_cmd(self, ignoreErrors=False, ignoreRequired=False,
+ ignoreDefault=True):
+ """Produce an array of command name and arguments for feeding
into some execve-like command processor.
- @param ignoreErrors True to return whatever has been built so
- far, even though it would not be a correct command for GRASS
- @param ignoreRequired True to ignore required flags, otherwise
- '@<required@>' is shown
- @param ignoreDefault True to ignore parameters with default values
+ :param bool ignoreErrors: True to return whatever has been built so
+ far, even though it would not be a correct
+ command for GRASS
+ :param bool ignoreRequired: True to ignore required flags, otherwise
+ '@<required@>' is shown
+ :param bool ignoreDefault: True to ignore parameters with default values
"""
cmd = [self.get_name()]
-
+
suppress_required = False
for flag in self.flags:
if flag['value']:
- if len(flag['name']) > 1: # e.g. overwrite
- cmd += [ '--' + flag['name'] ]
+ if len(flag['name']) > 1: # e.g. overwrite
+ cmd += ['--' + flag['name']]
else:
- cmd += [ '-' + flag['name'] ]
+ cmd += ['-' + flag['name']]
if flag['suppress_required']:
suppress_required = True
for p in self.params:
- if p.get('value', '') == '' and p.get('required', False):
- if p.get('default', '') != '':
- cmd += [ '%s=%s' % (p['name'], p['default']) ]
+ if p.get('value', '') == '' and p.get('required', False):
+ if p.get('default', '') != '':
+ cmd += ['%s=%s' % (p['name'], p['default'])]
elif ignoreErrors and not suppress_required and not ignoreRequired:
cmd += [('%s=%s' % (p['name'], _('<required>'))).decode('utf-8')]
- elif p.get('value', '') == '' and p.get('default', '') != '' and not ignoreDefault:
- cmd += [ '%s=%s' % (p['name'], p['default']) ]
- elif p.get('value', '') != '' and \
- (p['value'] != p.get('default', '') or not ignoreDefault):
+ elif p.get('value', '') == '' and p.get('default', '') != '' and not ignoreDefault:
+ cmd += ['%s=%s' % (p['name'], p['default'])]
+ elif p.get('value', '') != '' and \
+ (p['value'] != p.get('default', '') or not ignoreDefault):
# output only values that have been set, and different from defaults
- cmd += [ '%s=%s' % (p['name'], p['value']) ]
-
+ cmd += ['%s=%s' % (p['name'], p['value'])]
+
errList = self.get_cmd_error()
if ignoreErrors is False and errList:
raise ValueError, '\n'.join(errList)
-
+
return cmd
def get_options(self):
- """!Get options
+ """Get options
"""
- return { 'flags' : self.flags,
- 'params' : self.params }
-
+ return {'flags': self.flags, 'params': self.params}
+
def has_required(self):
- """!Check if command has at least one required paramater
+ """Check if command has at least one required paramater
"""
for p in self.params:
if p.get('required', False):
return True
-
+
return False
-
- def set_param(self, aParam, aValue, element = 'value'):
- """!Set param value/values.
+
+ def set_param(self, aParam, aValue, element='value'):
+ """Set param value/values.
"""
try:
param = self.get_param(aParam)
except ValueError:
return
-
+
param[element] = aValue
- def set_flag(self, aFlag, aValue, element = 'value'):
- """!Enable / disable flag.
+ def set_flag(self, aFlag, aValue, element='value'):
+ """Enable / disable flag.
"""
try:
param = self.get_flag(aFlag)
except ValueError:
return
-
+
param[element] = aValue
def set_options(self, opts):
- """!Set flags and parameters
+ """Set flags and parameters
- @param opts list of flags and parameters"""
+ :param opts list of flags and parameters"""
for opt in opts:
- if opt[0] == '-': # flag
+ if opt[0] == '-': # flag
self.set_flag(opt.lstrip('-'), True)
- else: # parameter
+ else: # parameter
key, value = opt.split('=', 1)
self.set_param(key, value)
-
+
+
class processTask:
- """!A ElementTree handler for the --interface-description output,
+ """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.
- @param tree root tree node
- @param task grassTask instance or None
- @param blackList list of flags/params to hide
-
- @return grassTask instance
+ :param tree: root tree node
+ :param task: grassTask instance or None
+ :param blackList: list of flags/params to hide
+
+ :return: grassTask instance
"""
- def __init__(self, tree, task = None, blackList = None):
+ def __init__(self, tree, task=None, blackList=None):
if task:
self.task = task
else:
self.task = grassTask()
if blackList:
self.task.blackList = blackList
-
+
self.root = tree
-
+
self._process_module()
self._process_params()
self._process_flags()
self.task.define_first()
-
+
def _process_module(self):
- """!Process module description
+ """Process module description
"""
- self.task.name = self.root.get('name', default = 'unknown')
-
+ self.task.name = self.root.get('name', default='unknown')
+
# keywords
for keyword in self._get_node_text(self.root, 'keywords').split(','):
self.task.keywords.append(keyword.strip())
-
- self.task.label = self._get_node_text(self.root, 'label')
+
+ self.task.label = self._get_node_text(self.root, 'label')
self.task.description = self._get_node_text(self.root, 'description')
-
+
def _process_params(self):
- """!Process parameters
+ """Process parameters
"""
for p in self.root.findall('parameter'):
# gisprompt
@@ -337,10 +335,10 @@
age = element = prompt = None
if node_gisprompt is not None:
gisprompt = True
- age = node_gisprompt.get('age', '')
+ age = node_gisprompt.get('age', '')
element = node_gisprompt.get('element', '')
- prompt = node_gisprompt.get('prompt', '')
-
+ prompt = node_gisprompt.get('prompt', '')
+
# value(s)
values = []
values_desc = []
@@ -351,30 +349,30 @@
desc = self._get_node_text(pv, 'description')
if desc:
values_desc.append(desc)
-
+
# keydesc
key_desc = []
node_key_desc = p.find('keydesc')
if node_key_desc is not None:
for ki in node_key_desc.findall('item'):
key_desc.append(ki.text)
-
- if p.get('multiple', 'no') == 'yes':
+
+ if p.get('multiple', 'no') == 'yes':
multiple = True
else:
multiple = False
- if p.get('required', 'no') == 'yes':
+ if p.get('required', 'no') == 'yes':
required = True
else:
required = False
-
+
if self.task.blackList['enabled'] and \
self.task.name in self.task.blackList['items'] and \
p.get('name') in self.task.blackList['items'][self.task.name].get('params', []):
hidden = True
else:
hidden = False
-
+
self.task.params.append( {
"name" : p.get('name'),
"type" : p.get('type'),
@@ -395,9 +393,9 @@
"key_desc" : key_desc,
"hidden" : hidden
})
-
+
def _process_flags(self):
- """!Process flags
+ """Process flags
"""
for p in self.root.findall('flag'):
if self.task.blackList['enabled'] and \
@@ -406,12 +404,12 @@
hidden = True
else:
hidden = False
-
+
if p.find('suppress_required') is not None:
suppress_required = True
else:
suppress_required = False
-
+
self.task.flags.append( {
"name" : p.get('name'),
"label" : self._get_node_text(p, 'label'),
@@ -421,141 +419,156 @@
"value" : False,
"hidden" : hidden
} )
-
- def _get_node_text(self, node, tag, default = ''):
- """!Get node text"""
+
+ def _get_node_text(self, node, tag, default=''):
+ """Get node text"""
p = node.find(tag)
if p is not None:
return string.join(string.split(p.text), ' ')
-
+
return default
-
+
def get_task(self):
- """!Get grassTask instance"""
+ """Get grassTask instance"""
return self.task
+
def convert_xml_to_utf8(xml_text):
# enc = locale.getdefaultlocale()[1]
-
+
# modify: fetch encoding from the interface description text(xml)
# e.g. <?xml version="1.0" encoding="GBK"?>
pattern = re.compile('<\?xml[^>]*\Wencoding="([^"]*)"[^>]*\?>')
m = re.match(pattern, xml_text)
- if m == None:
+ if m is None:
return xml_text
#
enc = m.groups()[0]
-
+
# modify: change the encoding to "utf-8", for correct parsing
xml_text_utf8 = xml_text.decode(enc).encode("utf-8")
p = re.compile('encoding="' + enc + '"', re.IGNORECASE)
xml_text_utf8 = p.sub('encoding="utf-8"', xml_text_utf8)
-
+
return xml_text_utf8
+
def get_interface_description(cmd):
- """!Returns the XML description for the GRASS cmd (force text encoding to "utf-8").
+ """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.
- @param cmd command (name of GRASS module)
+ :param cmd: command (name of GRASS module)
"""
try:
- p = Popen([cmd, '--interface-description'], stdout = PIPE,
- stderr = PIPE)
+ p = Popen([cmd, '--interface-description'], stdout=PIPE,
+ stderr=PIPE)
cmdout, cmderr = p.communicate()
-
+
# TODO: do it better (?)
if not cmdout and sys.platform == 'win32':
# we in fact expect pure module name (without extension)
# so, lets remove extension
if cmd.endswith('.py'):
cmd = os.path.splitext(cmd)[0]
-
+
if cmd == 'd.rast3d':
- sys.path.insert(0, os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'scripts'))
-
- p = Popen([sys.executable, get_real_command(cmd), '--interface-description'],
- stdout = PIPE, stderr = PIPE)
+ sys.path.insert(0, os.path.join(os.getenv('GISBASE'), 'etc',
+ 'gui', 'scripts'))
+
+ p = Popen([sys.executable, get_real_command(cmd),
+ '--interface-description'],
+ stdout=PIPE, stderr=PIPE)
cmdout, cmderr = p.communicate()
-
+
if cmd == 'd.rast3d':
- del sys.path[0] # remove gui/scripts from the path
-
+ del sys.path[0] # remove gui/scripts from the path
+
if p.returncode != 0:
raise ScriptError, _("Unable to fetch interface description for command '%(cmd)s'."
- "\n\nDetails: %(det)s") % { 'cmd' : cmd, 'det' : decode(cmderr) }
-
+ "\n\nDetails: %(det)s") % {'cmd': cmd, 'det': decode(cmderr)}
+
except OSError as e:
raise ScriptError, _("Unable to fetch interface description for command '%(cmd)s'."
- "\n\nDetails: %(det)s") % { 'cmd' : cmd, 'det' : e }
-
- desc = cmdout.replace('grass-interface.dtd', os.path.join(os.getenv('GISBASE'), 'gui', 'xml', 'grass-interface.dtd'))
+ "\n\nDetails: %(det)s") % {'cmd': cmd, 'det': e}
+
+ desc = cmdout.replace('grass-interface.dtd',
+ os.path.join(os.getenv('GISBASE'),
+ 'gui', 'xml',
+ 'grass-interface.dtd'))
return convert_xml_to_utf8(desc)
-def parse_interface(name, parser = processTask, blackList = None):
- """!Parse interface of given GRASS module
-
- @param name name of GRASS module to be parsed
+
+def parse_interface(name, parser=processTask, blackList=None):
+ """Parse interface of given GRASS module
+
+ :param str name: name of GRASS module to be parsed
+ :param parser:
+ :param blackList:
"""
tree = etree.fromstring(get_interface_description(name))
- return parser(tree, blackList = blackList).get_task()
+ return parser(tree, blackList=blackList).get_task()
+
def command_info(cmd):
- """!Returns meta information for any GRASS command as dictionary
+ """Returns meta information for any GRASS command as dictionary
with entries for description, keywords, usage, flags, and
parameters, e.g.
-
- @code
- >>> gtask.command_info('g.tempfile')
-
- {'keywords': ['general', 'map management'],
- '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': '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 the file name.',
- 'usage': 'g.tempfile pid=integer [--verbose] [--quiet]'
- }
- >>> gtask.command_info('v.buffer')['keywords']
-
+ >>> 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']
- @endcode
+
+ :param str cmd: the command to query
"""
task = parse_interface(cmd)
cmdinfo = {}
-
+
cmdinfo['description'] = task.get_description()
- cmdinfo['keywords'] = task.get_keywords()
- cmdinfo['flags'] = flags = task.get_options()['flags']
- cmdinfo['params'] = params = task.get_options()['params']
-
+ cmdinfo['keywords'] = task.get_keywords()
+ cmdinfo['flags'] = flags = task.get_options()['flags']
+ cmdinfo['params'] = params = task.get_options()['params']
+
usage = task.get_name()
flags_short = list()
- flags_long = list()
+ flags_long = list()
for f in flags:
fname = f.get('name', 'unknown')
if len(fname) > 1:
flags_long.append(fname)
else:
flags_short.append(fname)
-
+
if len(flags_short) > 1:
usage += ' [-' + ''.join(flags_short) + ']'
-
+
for p in params:
ptype = ','.join(p.get('key_desc', []))
if not ptype:
ptype = p.get('type', '')
- req = p.get('required', False)
+ req = p.get('required', False)
if not req:
- usage += ' ['
+ usage += ' ['
else:
usage += ' '
usage += p['name'] + '=' + ptype
@@ -563,10 +576,10 @@
usage += '[,' + ptype + ',...]'
if not req:
usage += ']'
-
+
for key in flags_long:
usage += ' [--' + key + ']'
-
+
cmdinfo['usage'] = usage
-
+
return cmdinfo
Modified: grass/trunk/lib/python/script/utils.py
===================================================================
--- grass/trunk/lib/python/script/utils.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/utils.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -1,25 +1,20 @@
-"""!@package grass.script.utils
-
- at brief GRASS Python scripting module (various useful functions)
-
+"""
Useful functions to be used in Python scripts.
Usage:
- at code
-from grass.script import utils as gutils
+::
-...
- at endcode
+ 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.
- at author Glynn Clements
- at author Martin Landa <landa.martin gmail.com>
- at author Anna Petrasova <kratochanna gmail.com>
+.. sectionauthor:: Glynn Clements
+.. sectionauthor:: Martin Landa <landa.martin gmail.com>
+.. sectionauthor:: Anna Petrasova <kratochanna gmail.com>
"""
import os
@@ -28,22 +23,22 @@
def float_or_dms(s):
- """!Convert DMS to float.
+ """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
- @param s DMS value
+ :param s: DMS value
- @return float value
+ :return: float value
"""
return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
def separator(sep):
- """!Returns separator from G_OPT_F_SEP appropriately converted
+ """Returns separator from G_OPT_F_SEP appropriately converted
to character.
>>> separator('pipe')
@@ -57,9 +52,9 @@
>>> separator(', ')
', '
- @param separator character or separator keyword
+ :param str separator: character or separator keyword
- @return separator character
+ :return: separator character
"""
if sep == "pipe":
return "|"
@@ -75,12 +70,12 @@
def diff_files(filename_a, filename_b):
- """!Diffs two text files and returns difference.
+ """Diffs two text files and returns difference.
- @param filename_a first file path
- @param filename_b second file path
+ :param str filename_a: first file path
+ :param str filename_b: second file path
- @return list of strings
+ :return: list of strings
"""
import difflib
differ = difflib.Differ()
@@ -92,10 +87,10 @@
def try_remove(path):
- """!Attempt to remove a file; no exception is generated if the
+ """Attempt to remove a file; no exception is generated if the
attempt fails.
- @param path path to file to remove
+ :param str path: path to file to remove
"""
try:
os.remove(path)
@@ -104,10 +99,10 @@
def try_rmdir(path):
- """!Attempt to remove a directory; no exception is generated if the
+ """Attempt to remove a directory; no exception is generated if the
attempt fails.
- @param path path to directory to remove
+ :param str path: path to directory to remove
"""
try:
os.rmdir(path)
@@ -116,11 +111,11 @@
def basename(path, ext=None):
- """!Remove leading directory components and an optional extension
+ """Remove leading directory components and an optional extension
from the specified path
- @param path path
- @param ext extension
+ :param str path: path
+ :param str ext: extension
"""
name = os.path.basename(path)
if not ext:
@@ -137,7 +132,6 @@
KeyValue is a subclass of dict, but also allows entries to be read and
written using attribute syntax. Example:
- \code
>>> reg = KeyValue()
>>> reg['north'] = 489
>>> reg.north
@@ -145,8 +139,6 @@
>>> reg.south = 205
>>> reg['south']
205
-
- \endcode
"""
def __getattr__(self, key):
@@ -157,7 +149,7 @@
def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
- """!Parse a string into a dictionary, where entries are separated
+ """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'}
@@ -166,13 +158,13 @@
... val_type=float) == {'min': 20, 'max': 50}
True
- @param s string to be parsed
- @param sep key/value separator
- @param dflt default value to be used
- @param val_type value type (None for no cast)
- @param vsep vertical separator (default is Python 'universal newlines' approach)
+ :param str s: string to be parsed
+ :param str sep: key/value separator
+ :param dflt: default value to be used
+ :param val_type: value type (None for no cast)
+ :param vsep: vertical separator (default is Python 'universal newlines' approach)
- @return parsed input (dictionary of keys/values)
+ :return: parsed input (dictionary of keys/values)
"""
result = KeyValue()
@@ -205,6 +197,10 @@
def decode(string):
+ """Decode string with defualt locale
+
+ :param str string: the string to decode
+ """
enc = locale.getdefaultlocale()[1]
if enc:
return string.decode(enc)
@@ -213,6 +209,10 @@
def encode(string):
+ """Encode string with defualt locale
+
+ :param str string: the string to encode
+ """
enc = locale.getdefaultlocale()[1]
if enc:
return string.encode(enc)
Modified: grass/trunk/lib/python/script/vector.py
===================================================================
--- grass/trunk/lib/python/script/vector.py 2014-09-13 21:27:42 UTC (rev 61916)
+++ grass/trunk/lib/python/script/vector.py 2014-09-13 21:45:23 UTC (rev 61917)
@@ -1,25 +1,20 @@
-"""!@package grass.script.vector
-
- at brief GRASS Python scripting module (vector functions)
-
+"""
Vector related functions to be used in Python scripts.
Usage:
- at code
-from grass.script import vector as grass
+::
-grass.vector_db(map)
-...
- at endcode
+ 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.
- at author Glynn Clements
- at author Martin Landa <landa.martin gmail.com>
+.. sectionauthor:: Glynn Clements
+.. sectionauthor:: Martin Landa <landa.martin gmail.com>
"""
import os
@@ -30,32 +25,28 @@
from utils import parse_key_val
from core import *
-# run "v.db.connect -g ..." and parse output
def vector_db(map, **args):
- """!Return the database connection details for a vector map
+ """Return the database connection details for a vector map
(interface to `v.db.connect -g'). Example:
-
- \code
- >>> grass.vector_db('lakes')
- {1: {'layer': 1, 'name': '',
- 'database': '/home/martin/grassdata/nc_spm_08/PERMANENT/dbf/',
- 'driver': 'dbf', 'key': 'cat', 'table': 'lakes'}}
- \endcode
-
- @param map vector map
- @param args other v.db.connect's arguments
-
- @return dictionary
+
+ >>> vector_db('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
+ {1: {'layer': 1, ... 'table': 'geology'}}
+
+ :param str map: vector map
+ :param args: other v.db.connect's arguments
+
+ :return: dictionary
"""
- s = read_command('v.db.connect', quiet = True, flags = 'g', map = map, sep = ';', **args)
+ s = read_command('v.db.connect', quiet=True, flags='g', map=map, sep=';',
+ **args)
result = {}
-
+
for l in s.splitlines():
f = l.split(';')
if len(f) != 5:
continue
-
+
if '/' in f[0]:
f1 = f[0].split('/')
layer = f1[0]
@@ -63,7 +54,7 @@
else:
layer = f[0]
name = ''
-
+
result[int(layer)] = {
'layer' : int(layer),
'name' : name,
@@ -71,17 +62,18 @@
'key' : f[2],
'database' : f[3],
'driver' : f[4] }
-
+
return result
+
def vector_layer_db(map, layer):
- """!Return the database connection details for a vector map layer.
+ """Return the database connection details for a vector map layer.
If db connection for given layer is not defined, fatal() is called.
-
- @param map map name
- @param layer layer number
-
- @return parsed output
+
+ :param str map: map name
+ :param layer: layer number
+
+ :return: parsed output
"""
try:
f = vector_db(map)[int(layer)]
@@ -92,27 +84,40 @@
# run "v.info -c ..." and parse output
-def vector_columns(map, layer = None, getDict = True, **args):
- """!Return a dictionary (or a list) of the columns for the
+
+def vector_columns(map, layer=None, getDict=True, **args):
+ """Return a dictionary (or a list) of the columns for the
database table connected to a vector map (interface to `v.info
-c').
- @code
- >>> vector_columns(urbanarea, getDict = True)
- {'UA_TYPE': {'index': 4, 'type': 'CHARACTER'}, 'UA': {'index': 2, 'type': 'CHARACTER'}, 'NAME': {'index': 3, 'type': 'CHARACTER'}, 'OBJECTID': {'index': 1, 'type': 'INTEGER'}, 'cat': {'index': 0, 'type': 'INTEGER'}}
+ >>> 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(urbanarea, getDict = False)
- ['cat', 'OBJECTID', 'UA', 'NAME', 'UA_TYPE']
- @endcode
-
- @param map map name
- @param layer layer number or name (None for all layers)
- @param getDict True to return dictionary of columns otherwise list of column names is returned
- @param args (v.info's arguments)
-
- @return dictionary/list of columns
+ >>> vector_columns('geology', getDict=False) # doctest: +NORMALIZE_WHITESPACE
+ ['cat',
+ 'onemap_pro',
+ 'PERIMETER',
+ 'GEOL250_',
+ 'GEOL250_ID',
+ 'GEO_NAME',
+ 'SHAPE_area',
+ 'SHAPE_len']
+
+ :param str map: map name
+ :param layer: layer number or name (None for all layers)
+ :param bool getDict: True to return dictionary of columns otherwise list
+ of column names is returned
+ :param args: (v.info's arguments)
+
+ :return: dictionary/list of columns
"""
- s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
+ s = read_command('v.info', flags='c', map=map, layer=layer, quiet=True,
+ **args)
if getDict:
result = dict()
else:
@@ -121,85 +126,67 @@
for line in s.splitlines():
ctype, cname = line.split('|')
if getDict:
- result[cname] = { 'type' : ctype,
- 'index' : i }
+ result[cname] = {'type': ctype, 'index': i}
else:
result.append(cname)
- i+=1
-
+ i += 1
+
return result
-# add vector history
def vector_history(map):
- """!Set the command history for a vector map to the command used to
+ """Set the command history for a vector map to the command used to
invoke the script (interface to `v.support').
- @param map mapname
+ :param str map: mapname
- @return v.support output
+ :return: v.support output
"""
- run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+ run_command('v.support', map=map, cmdhist=os.environ['CMDLINE'])
-# run "v.info -t" and parse output
def vector_info_topo(map):
- """!Return information about a vector map (interface to `v.info
+ """Return information about a vector map (interface to `v.info
-t'). Example:
- \code
- >>> grass.vector_info_topo('lakes')
- {'kernels': 0, 'lines': 0, 'centroids': 15279,
- 'boundaries': 27764, 'points': 0, 'faces': 0,
- 'primitives': 43043, 'islands': 7470, 'nodes': 35234, 'map3d': False, 'areas': 15279}
- \endcode
-
- @param map map name
+ >>> 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}
- @return parsed output
+ :param str map: map name
+
+ :return: parsed output
"""
- s = read_command('v.info', flags = 't', map = map)
- ret = parse_key_val(s, val_type = int)
+ s = read_command('v.info', flags='t', map=map)
+ ret = parse_key_val(s, val_type=int)
if 'map3d' in ret:
ret['map3d'] = bool(ret['map3d'])
-
+
return ret
-# run "v.info -get ..." and parse output
-
def vector_info(map):
- """!Return information about a vector map (interface to
+ """Return information about a vector map (interface to
`v.info'). Example:
- \code
- >>> grass.vector_info('random_points')
- {'comment': '', 'projection': 'x,y', 'creator': 'soeren', 'holes': 0,
- 'primitives': 20, 'kernels': 0, 'scale': '1:1', 'title': '',
- 'west': 0.046125489999999998, 'top': 2376.133159, 'boundaries': 0,
- 'location': 'XYLocation', 'nodes': 0, 'east': 0.97305646000000001,
- 'source_date': 'Mon Aug 29 10:55:57 2011', 'north': 0.9589993,
- 'format': 'native', 'faces': 0, 'centroids': 0,
- 'digitization_threshold': '0.000000', 'islands': 0, 'level': 2,
- 'mapset': 'test', 'areas': 0, 'name': 'random_points',
- 'database': '/home/soeren/grassdata', 'bottom': 22.186596999999999,
- 'lines': 0, 'points': 20, 'map3d': True, 'volumes': 0, 'num_dblinks': 0,
- 'organization': '', 'south': 0.066047099999999997}
-
- \endcode
- @param map map name
-
- @return parsed vector info
+ >>> vector_info('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
+ {'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917}
+
+ :param str map: map name
+
+ :return: parsed vector info
"""
- s = read_command('v.info', flags = 'get', map = map)
-
+ s = read_command('v.info', flags='get', map=map)
+
kv = parse_key_val(s)
for k in ['north', 'south', 'east', 'west', 'top', 'bottom']:
kv[k] = float(kv[k])
for k in ['level', 'num_dblinks']:
kv[k] = int(kv[k])
- for k in ['nodes', 'points', 'lines', 'boundaries', 'centroids', 'areas', 'islands', 'primitives']:
+ for k in ['nodes', 'points', 'lines', 'boundaries', 'centroids', 'areas',
+ 'islands', 'primitives']:
kv[k] = int(kv[k])
if 'map3d' in kv:
kv['map3d'] = bool(int(kv['map3d']))
@@ -210,36 +197,32 @@
return kv
-# interface for v.db.select
+def vector_db_select(map, layer=1, **kwargs):
+ """Get attribute data of selected vector map layer.
-def vector_db_select(map, layer = 1, **kwargs):
- """!Get attribute data of selected vector map layer.
-
Function returns list of columns and dictionary of values ordered by
key column value. Example:
- \code
- >>> print grass.vector_db_select('lakes')['columns']
- ['cat', 'AREA', 'PERIMETER', 'FULL_HYDRO', 'FULL_HYDR2', 'FTYPE', 'FCODE', 'NAME']
- >>> print grass.vector_db_select('lakes')['values'][3]
- ['3', '19512.86146', '708.44683', '4', '55652', 'LAKE/POND', '39000', '']
- >>> print grass.vector_db_select('lakes', columns = 'FTYPE')['values'][3]
- ['LAKE/POND']
- \endcode
+ >>> 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']
- @param map map name
- @param layer layer number
- @param kwargs v.db.select options
+ :param str map: map name
+ :param str layer: layer number
+ :param kwargs: v.db.select options
- @return dictionary ('columns' and 'values')
+ :return: dictionary ('columns' and 'values')
"""
try:
- key = vector_db(map = map)[layer]['key']
+ key = vector_db(map=map)[layer]['key']
except KeyError:
error(_('Missing layer %(layer)d in vector map <%(map)s>') % \
- { 'layer' : layer, 'map' : map })
- return { 'columns' : [], 'values' : {} }
-
+ {'layer': layer, 'map': map})
+ return {'columns': [], 'values': {}}
+
include_key = True
if 'columns' in kwargs:
if key not in kwargs['columns'].split(','):
@@ -247,16 +230,13 @@
include_key = False
debug("Adding key column to the output")
kwargs['columns'] += ',' + key
-
- ret = read_command('v.db.select',
- map = map,
- layer = layer,
- **kwargs)
-
+
+ ret = read_command('v.db.select', map=map, layer=layer, **kwargs)
+
if not ret:
error(_('vector_db_select() failed'))
- return { 'columns' : [], 'values' : {} }
-
+ return {'columns': [], 'values': {}}
+
columns = []
values = {}
for line in ret.splitlines():
@@ -265,9 +245,9 @@
key_index = columns.index(key)
# discard key column
if not include_key:
- columns = columns[:-1]
+ columns = columns[:-1]
continue
-
+
value = line.split('|')
key_value = int(value[key_index])
if not include_key:
@@ -275,60 +255,68 @@
values[key_value] = value[:-1]
else:
values[key_value] = value
-
- return { 'columns' : columns,
- 'values' : values }
-# interface to v.what
-def vector_what(map, coord, distance = 0.0, ttype = None):
- """!Query vector map at given locations
-
+ return {'columns': columns, 'values': values}
+
+
+def vector_what(map, coord, distance=0.0, ttype=None):
+ """Query vector map at given locations
+
To query one vector map at one location
- @code
- 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}]
- @endcode
+ ::
- To query one vector map with multiple layers (no additional parameters required)
- @code
- for q in grass.vector_what(map = 'some_map', coord = (596532.357143,4920486.21429), distance = 100.0):
- print q['Map'], q['Layer'], q['Attributes']
+ print grass.vector_what(map='archsites', coord=(595743, 4925281),
+ distance=250)
- new_bug_sites 1 {'str1': 'Beetle_site', 'GRASSRGB': '', 'cat': '80'}
- new_bug_sites 2 {'cat': '80'}
- @endcode
+ [{'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
- @code
- 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'}
- @endcode
+ ::
+
+ 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
- @code
- for q in grass.vector_what(map = 'archsites', coord = [(595743, 4925281), (597950, 4918898)],
- distance = 250):
- print q['Map'], q['Attributes']
- archsites {'str1': 'No_Name', 'cat': '8'}
- archsites {'str1': 'Bob_Miller', 'cat': '22'}
- @endcode
+ ::
- @param map vector map(s) to query given as string or list/tuple
- @param coord coordinates of query given as tuple (easting, northing) or list of tuples
- @param distance query threshold distance (in map units)
- @param ttype list of topology types (default of v.what are point, line, area, face)
+ for q in grass.vector_what(map='archsites', distance=250,
+ coord=[(595743, 4925281), (597950, 4918898)]):
+ print q['Map'], q['Attributes']
- @return parsed list
+ archsites {'str1': 'No_Name', 'cat': '8'}
+ archsites {'str1': 'Bob_Miller', 'cat': '22'}
+
+ :param map: vector map(s) to query given as string or list/tuple
+ :param coord: coordinates of query given as tuple (easting, northing) or
+ list of tuples
+ :param distance: query threshold distance (in map units)
+ :param ttype: list of topology types (default of v.what are point, line,
+ area, face)
+
+ :return: parsed list
"""
if "LC_ALL" in os.environ:
locale = os.environ["LC_ALL"]
@@ -338,16 +326,16 @@
map_list = [map]
else:
map_list = map
-
+
layer_list = ['-1'] * len(map_list)
-
+
coord_list = list()
if type(coord) is types.TupleType:
coord_list.append('%f,%f' % (coord[0], coord[1]))
else:
for e, n in coord:
coord_list.append('%f,%f' % (e, n))
-
+
cmdParams = dict(quiet = True,
flags = 'ag',
map = ','.join(map_list),
@@ -359,14 +347,14 @@
ret = read_command('v.what',
**cmdParams)
-
+
if "LC_ALL" in os.environ:
os.environ["LC_ALL"] = locale
-
+
data = list()
if not ret:
return data
-
+
# parse `v.what -g` output is a nightmare
# TODO: change `v.what -g` format or add parsable format (e.g. XML)
dict_attrb = None
@@ -380,7 +368,7 @@
continue
if key in ('East', 'North'):
continue
-
+
if key == 'Map':
# attach the last one from the previous map
if dict_map is not None:
@@ -388,7 +376,7 @@
if dict_layer is not None:
dict_main.update(dict_layer)
data.append(dict_main)
- dict_map = { key : value }
+ dict_map = {key : value}
dict_layer = None
dict_attrb = None
elif key == 'Layer':
@@ -398,7 +386,7 @@
dict_main = copy.copy(dict_map)
dict_main.update(dict_layer)
data.append(dict_main)
- dict_layer = { key: int(value) }
+ dict_layer = {key: int(value)}
dict_attrb = None
else:
dict_attrb[key] = value
@@ -417,12 +405,12 @@
dict_map[key] = value
# TODO: there are some keys which has non-string values
# examples: Sq_Meters, Hectares, Acres, Sq_Miles
-
+
# attach the last one
if dict_map is not None:
dict_main = copy.copy(dict_map)
if dict_layer:
dict_main.update(dict_layer)
data.append(dict_main)
-
+
return data
More information about the grass-commit
mailing list