1g.parser(1)                 GRASS GIS User's Manual                g.parser(1)
2
3
4

NAME

6       g.parser - Provides full parser support for GRASS scripts.
7

KEYWORDS

9       general, support, scripts
10

SYNOPSIS

12       g.parser --help
13       g.parser [-s] [-t]  [-n] filename [argument,...]
14
15   Flags:
16       -t
17           Print strings for translation
18
19       -s
20           Write option values to standard output instead of reinvoking script
21
22       -n
23           Write option values to standard output separated by null character
24

DESCRIPTION

26       The g.parser module provides full parser support for GRASS scripts, in‐
27       cluding an auto-generated GUI interface, help page template,  and  com‐
28       mand line option checking. In this way a simple script can very quickly
29       be made into a full-fledged GRASS module.
30

OPTIONS

32       Unless the -s or -n switch is used, the arguments are stored  in  envi‐
33       ronment  variables  for  use in your scripts. These variables are named
34       "GIS_FLAG_<NAME>" for flags and "GIS_OPT_<NAME>" for options. The names
35       of variables are converted to upper case. For example if an option with
36       key input was defined in the script header, the value will be available
37       in  variable  GIS_OPT_INPUT  and  the  value of flag with key f will be
38       available in variable GIS_FLAG_F.
39
40       For flags, the value will be "1" if the flag was given, and "0"  other‐
41       wise.
42
43       If  the  -s  or -n switch is used, the options and flags are written to
44       standard output in the form opt_<name>=<value> and flag_<name>=<value>,
45       preceded  by the string @ARGS_PARSED@. If this string doesn’t appear as
46       the first line of standard output, it indicates that the script was in‐
47       voked  with a switch such as --html-description. In this case, the data
48       written by g.parser to standard output should be copied to the script’s
49       standard  output  verbatim.   If the -s switch is used, the options and
50       flags are separated by newlines. If the -n switch is used, the  options
51       and flags are separated by null characters.
52
53       Typical header definitions are as follows:
54       # %module
55       # % description: g.parser test script
56       # %end
57       # %flag
58       # % key: f
59       # % description: A flag
60       # %end
61       # %option
62       # % key: raster
63       # % type: string
64       # % gisprompt: old,cell,raster
65       # % description: Raster input map
66       # % required: yes
67       # %end
68       With  {NULL} it is possible to suppress a predefined description or la‐
69       bel.
70
71       The parsers allows using predefined standardized options and flags, see
72       the list of options and flags in the programmer manual. Eg. the option
73       # %option
74       # % key: raster
75       # % type: string
76       # % gisprompt: old,cell,raster
77       # % description: Raster input map
78       # % required: yes
79       # %end
80       can be easily defined as
81       # %option G_OPT_R_MAP
82       # % key: raster
83       # %end
84       The parser allows defining predefined rules for used options.  The syn‐
85       tax of the rules section is following:
86       # %rules
87       # % exclusive: capfile_output, capfile
88       # %end
89       The parser also allows defining "OR" conditions, e.g. requiring  raster
90       OR vector (for details, see below), e.g.for options:
91       # %rules
92       # % required: raster, vector
93       # %end
94       and e.g., for flags:
95       # %rules
96       # % required: -i,-d,-c
97       # %end
98

NOTES

100       An option can be instructed to allow multiple inputs by adding the fol‐
101       lowing line:
102       # % multiple: yes
103       While this will only directly change the  Usage  section  of  the  help
104       screen,  the  option’s  environmental  string may be easily parsed from
105       within a script. For example, individual comma separated identities for
106       an  option  named  "input"  can be parsed with the following Bash shell
107       code:
108       IFS=,
109       for opt in $GIS_OPT_INPUT ; do
110           ... "$opt"
111       done
112
113       A "guisection" field may be added to each option and  flag  to  specify
114       that  the  options should appear in multiple tabs in the auto-generated
115       GUI.  Any options without a guisection field go into the "Required"  or
116       "Options" tab.  For example:
117       # % guisection: tabname
118       would put that option in a tab named tabname.
119
120       A "key_desc" field may be added to each option to specify the text that
121       appears in the module’s usage help section. For example:
122       # % key_desc: filename
123       added to an input option would create the  usage  summary  [input=file‐
124       name].
125
126       If  a  script  is  run with --o, the parser will set GRASS_OVERWRITE=1,
127       which has the same effect as passing --o to every module which  is  run
128       from  the  script. Similarly, passing --q or --v will set GRASS_VERBOSE
129       to 0 or 3 respectively, which has the same effect as passing --q or --v
130       to  every  module  which  is run from the script.  Rather than checking
131       whether --o, --q or --v were used, you should be  checking  GRASS_OVER‐
132       WRITE  and/or  GRASS_VERBOSE  instead.  If those variables are set, the
133       script should behave the same way regardless of whether they  were  set
134       by --o, --q or --v being passed to the script or set by other means.
135
136       For  backwards compatibility reasons, the header definitions can use #%
137       instead of # % as in #% multiple: yes. However, Python code should  use
138       # % in order to conform to PEP8.
139

Conditional parameters

141       Marking an option as "required" will result in the parser raising a fa‐
142       tal error if the option is not given, with one exception: if a flag has
143       the  suppress_required option, and that flag is given, all requirements
144       are ignored. This feature is intended for flags which  abandon  "normal
145       operation"  for  the  module;  e.g. r.in.gdal’s -f flag (list supported
146       formats) uses it.
147       But in general, an option cannot be marked as required  if  it  is  op‐
148       tional  except  for  the special case of a suppress_required flag.  The
149       parser has the ability to specify option relationships.
150
151       For C, the relevant functions  are  those  in  lib/gis/parser_dependen‐
152       cies.c.
153
154       For scripts, relationships are specified using a "rules" section, e.g.
155       # %rules
156       # % required: altitude,elevation
157       # %end
158       specifies  that  at  least one of those options must be given. Both op‐
159       tions and flags can be specified (a leading "-" denotes a  flag).   The
160       available rule types are:
161
162           •   exclusive: at most one of the options may be given
163
164           •   required: at least one of the options must be given
165
166           •   requires:  if  the  first  option is given, at least one of the
167               subsequent options must also be given
168
169           •   requires_all: if the first option is given, all of  the  subse‐
170               quent options must also be given
171
172           •   excludes:  if the first option is given, none of the subsequent
173               options may be given
174
175           •   collective: all or nothing; if any option is given, all must be
176               given
177

AUTOMATED SCRIPT CREATION

179       The  flag --script added to a GRASS command, generates shell output. To
180       write out  a  g.parser  boilerplate  for  easy  prototyping  of  Python
181       scripts, the flag --script can be added to any GRASS command. Example:
182       v.in.db --script
183

Help page template (HTML)

185       The  flag  --html-description  added to a GRASS command generates a re‐
186       lated help page template in HTML. Example:
187       v.in.db --html-description
188

GUI window parser (XML)

190       The flag --interface-description added to a GRASS command  generates  a
191       related help page template in XML. Example:
192       v.in.db --interface-description
193

JSON

195       The flag --json added to a GRASS command with parameters mandatorily to
196       be specified generates a module interface description in JSON. Example:
197       v.in.db driver=sqlite database=mysqlite.db table=pointsfile x=x y=y z=z key=idcol out=dtmpoints --json
198       {
199         "module": "v.in.db",
200         "id": "v.in.db_1804289383",
201         "inputs":[
202            {"param": "table", "value": "pointsfile"},
203            {"param": "driver", "value": "sqlite"},
204            {"param": "database", "value": "mysqlite.db"},
205            {"param": "x", "value": "x"},
206            {"param": "y", "value": "y"},
207            {"param": "z", "value": "z"},
208            {"param": "key", "value": "idcol"}
209          ],
210         "outputs":[
211            {"param": "output", "value": "dtmpoints"}
212          ]
213       }
214

Web Processing Service (WPS)

216       The flag --wps-process-description added to a GRASS command generates a
217       Web Processing Service process description. Example:
218       v.in.db --wps-process-description
219

reStructuredText

221       The  flag  --rst-description  added to a GRASS command generates module
222       interface description in reStructuredText, a  lightweight  markup  lan‐
223       guage. Example:
224       v.in.db --rst-description
225       reStructuredText  is  sometimes abbreviated as reST, ReST, or RST.  The
226       commonly used file extension is .rst.  Don’t be confused with Represen‐
227       tational State Transfer (REST) technology.
228

TRANSLATION

230       g.parser  provides some support for translating the options of scripts.
231       If called with the -t switch before the script filename like this
232       g.parser -t somescriptfile
233       g.parser will print the text of the translatable  options  to  standard
234       output,  one  per  line,  and exit. This is for internal use within the
235       build system to prepare GRASS scripts for translation.
236

EXAMPLES

238       All examples below autogenerate the graphical user interface  when  in‐
239       voked without parameters of flags:
240
241       To  run properly, the script needs to be copied into a directory listed
242       in $GRASS_ADDON_PATH environmental variable with  the  executable  flag
243       being set.
244
245       The  script  will provide a GUI (as above) and the following usage help
246       text:
247       test.py|sh|pl --help
248       Description:
249        g.parser test script (python)
250       Usage:
251        test.sh [-f] raster=string vector=string [option1=string]
252          [--verbose] [--quiet]
253       Flags:
254         -f   A flag
255        --v   Verbose module output
256        --q   Quiet module output
257       Parameters:
258          raster   Raster input map
259          vector   Vector input map
260         option1   An option
261
262   Example code for Python
263       #!/usr/bin/env python3
264       # g.parser demo script for python programming
265       # %module
266       # % description: g.parser test script (python)
267       # % keyword: keyword1
268       # % keyword: keyword2
269       # %end
270       # %flag
271       # % key: f
272       # % description: A flag
273       # %end
274       # %option G_OPT_R_MAP
275       # % key: raster
276       # % required: yes
277       # %end
278       # %option G_OPT_V_MAP
279       # % key: vector
280       # %end
281       # %option
282       # % key: option1
283       # % type: string
284       # % description: An option
285       # % required: no
286       # %end
287       import os
288       import sys
289       import grass.script as gs
290       def main():
291           flag_f = flags[’f’]
292           option1 = options[’option1’]
293           raster = options[’raster’]
294           vector = options[’vector’]
295           #### add your code here ####
296           if flag_f:
297               print "Flag -f set"
298           else:
299               print "Flag -f not set"
300           # test if parameter present:
301           if option1:
302               print "Value of option1 option: ’%s’" % option1
303           print "Value of raster option: ’%s’" % raster
304           print "Value of vector option: ’%s’" % vector
305           #### end of your code ####
306           return 0
307       if __name__ == "__main__":
308           options, flags = gs.parser()
309           sys.exit(main())
310
311   Example code for SHELL
312       #!/bin/sh
313       # g.parser demo script for shell programming
314       # %module
315       # % description: g.parser test script (shell)
316       # %end
317       # %flag
318       # % key: f
319       # % description: A flag
320       # %end
321       # %option G_OPT_R_MAP
322       # % key: raster
323       # % required: yes
324       # %end
325       # %option G_OPT_V_MAP
326       # % key: vector
327       # %end
328       # %option
329       # % key: option1
330       # % type: string
331       # % description: An option
332       # % required: no
333       # %end
334       if [ -z "$GISBASE" ] ; then
335           echo "You must be in GRASS GIS to run this program." 1>&2
336           exit 1
337       fi
338       if [ "$1" != "@ARGS_PARSED@" ] ; then
339           exec g.parser "$0" "$@"
340       fi
341       #### add your code below ####
342       echo ""
343       if [ $GIS_FLAG_F -eq 1 ] ; then
344         g.message message="Flag -f set"
345       else
346         g.message message="Flag -f not set"
347       fi
348       # test if parameter present:
349       if [ -n "$GIS_OPT_OPTION1" ] ; then
350           echo "Value of GIS_OPT_OPTION1: ’$GIS_OPT_OPTION1’"
351       fi
352       g.message message="Value of GIS_OPT_option1: ’$GIS_OPT_option1’"
353       g.message message="Value of GIS_OPT_raster: ’$GIS_OPT_raster’"
354       g.message message="Value of GIS_OPT_vect: ’$GIS_OPT_vector’"
355       #### end of your code ####
356
357   Example code for Perl
358       #!/usr/bin/perl -w
359       use strict;
360       # g.parser demo script
361       # %module
362       # %  description: g.parser test script (perl)
363       # %  keyword: keyword1
364       # %  keyword: keyword2
365       # %end
366       # %flag
367       # %  key: f
368       # %  description: A flag
369       # %end
370       # %option G_OPT_R_MAP
371       # % key: raster
372       # % required: yes
373       # %end
374       # %option G_OPT_V_MAP
375       # % key: vector
376       # %end
377       # %option
378       # % key: option1
379       # % type: string
380       # % description: An option
381       # % required: no
382       # %end
383       if ( !$ENV{’GISBASE’} ) {
384           printf(STDERR  "You must be in GRASS GIS to run this program.\n");
385           exit 1;
386       }
387       if( $ARGV[0] ne ’@ARGS_PARSED@’ ){
388           my $arg = "";
389           for (my $i=0; $i < @ARGV;$i++) {
390               $arg .= " $ARGV[$i] ";
391           }
392           system("$ENV{GISBASE}/bin/g.parser $0 $arg");
393           exit;
394       }
395       #### add your code here ####
396       print  "\n";
397       if ( $ENV{’GIS_FLAG_F’} eq "1" ){
398          print "Flag -f set\n"
399       }
400       else {
401          print "Flag -f not set\n"
402       }
403       printf ("Value of GIS_OPT_option1: ’%s’\n", $ENV{’GIS_OPT_OPTION1’});
404       printf ("Value of GIS_OPT_raster: ’%s’\n", $ENV{’GIS_OPT_RASTER’});
405       printf ("Value of GIS_OPT_vect: ’%s’\n", $ENV{’GIS_OPT_VECTOR’});
406       #### end of your code ####
407
408   Easy creation of a script
409       By using the --script flag with any GRASS GIS module (must be run in  a
410       GRASS GIS session) header, description, keywords, parameters, flags and
411       a template main Python script section will be printed in  the  terminal
412       which can be saved to a file and used for further script programming.
413
414       In  this  example,  the  module v.what.rast is used as an example.  The
415       output is shown below:
416       v.what.rast --script
417       #!/usr/bin/env python3
418       ############################################################################
419       #
420       # MODULE:       v.what.rast_wrapper
421       # AUTHOR(S):    username
422       # PURPOSE:      Wrapper for v.what.rast
423       # COPYRIGHT:    (C) 2017 by username, and the GRASS Development Team
424       #
425       #  This program is free software; you can redistribute it and/or modify
426       #  it under the terms of the GNU General Public License as published by
427       #  the Free Software Foundation; either version 2 of the License, or
428       #  (at your option) any later version.
429       #
430       #  This program is distributed in the hope that it will be useful,
431       #  but WITHOUT ANY WARRANTY; without even the implied warranty of
432       #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
433       #  GNU General Public License for more details.
434       #
435       ############################################################################
436       # %module
437       # % description: Uploads raster values at positions of vector points to the table.
438       # % keyword: vector, sampling, raster, position, querying, attribute table, surface information
439       # %end
440       # %flag
441       # % key: i
442       # % description: Interpolate values from the nearest four cells
443       # %end
444       # %flag
445       # % key: p
446       # % description: Print categories and values instead of updating the database
447       # %end
448       # %option
449       # % key: map
450       # % type: string
451       # % required: yes
452       # % multiple: no
453       # % key_desc: name
454       # % label: Name of vector points map for which to edit attributes
455       # % description: Or data source for direct OGR access
456       # % gisprompt: old,vector,vector
457       # %end
458       # %option
459       # % key: layer
460       # % type: string
461       # % required: no
462       # % multiple: no
463       # % label: Layer number or name
464       # % description: Vector features can have category values in different layers. This number determines which layer to use. When used with direct OGR access this is the layer name.
465       # % answer: 1
466       # % gisprompt: old,layer,layer
467       # %end
468       # %option
469       # % key: type
470       # % type: string
471       # % required: no
472       # % multiple: yes
473       # % options: point,centroid
474       # % description: Input feature type
475       # % answer: point
476       # %end
477       # %option
478       # % key: raster
479       # % type: string
480       # % required: yes
481       # % multiple: no
482       # % key_desc: name
483       # % description: Name of existing raster map to be queried
484       # % gisprompt: old,cell,raster
485       # %end
486       # %option
487       # % key: column
488       # % type: string
489       # % required: no
490       # % multiple: no
491       # % key_desc: name
492       # % description: Name of attribute column to be updated with the query result
493       # % gisprompt: old,dbcolumn,dbcolumn
494       # %end
495       # %option
496       # % key: where
497       # % type: string
498       # % required: no
499       # % multiple: no
500       # % key_desc: sql_query
501       # % label: WHERE conditions of SQL statement without ’where’ keyword
502       # % description: Example: income < 1000 and population >= 10000
503       # %end
504       import sys
505       import grass.script as gs
506       def main():
507           # put code here
508           return 0
509       if __name__ == "__main__":
510           options, flags = gs.parser()
511           sys.exit(main())
512

SEE ALSO

514        g.filename, g.findfile, g.tempfile
515
516       Overview table: Parser standard options
517
518       Submitting rules for Python
519
520       Related Wiki pages: Using GRASS GIS with other programming languages
521

AUTHOR

523       Glynn Clements
524

SOURCE CODE

526       Available at: g.parser source code (history)
527
528       Accessed: Mon Jun 20 16:45:51 2022
529
530       Main index | General index | Topics index | Keywords index |  Graphical
531       index | Full index
532
533       © 2003-2022 GRASS Development Team, GRASS GIS 8.2.0 Reference Manual
534
535
536
537GRASS 8.2.0                                                        g.parser(1)
Impressum