Scripting: Difference between revisions

From GRASS-Wiki
Jump to navigation Jump to search
(init (needs work!))
 
Line 48: Line 48:


See the SUBMITTING_SCRIPTS file(s) for some tips.
See the SUBMITTING_SCRIPTS file(s) for some tips.
See the existing GRASS scripts in the scripts/ directory for examples of using tempfiles, etc.


Newer versions of Ubuntu use Dash as the default /bin/sh, so don't assume that sh will handle Bashisms.
Newer versions of Ubuntu use Dash as the default /bin/sh, so don't assume that sh will handle Bashisms.


=== Python ===
=== Python ===

Revision as of 09:50, 4 December 2007

Scripting

General

Verbosity level

Use the "--quiet" (alias --q) and "--verbose" (alias --v) command line arguments to make the script produce more or less messages and info like percent done. This works for almost all modules. The big exception to that is r.mapcalc which doesn't use the standard parser.

For r.mapcalc, or if you want to set a blanket --quiet directive for the whole script, you can set the GRASS_VERBOSE environmental variable. Python's os module has a putenv() function to do that.

These are the levels you can use:

 (from lib/gis/verbose.c)
0 - module should print nothing but errors and warnings (G_fatal_error,
     G_warning)  Triggered by "--q" or "--quiet".
1 - module will print progress information (G_percent)
2 - module will print all messages (G_message)  [default level]
3 - module will be very verbose. Triggered by "--v" or "--verbose".

"--quiet" will set the level to 0.


shell script example

# for everything that follows
GRASS_VERBOSE=1
export GRASS_VEBOSE
# override for just one module
GRASS_VERBOSE=0 \
  r.mapcalc "only_set = for_this_process"


Another nice thing about using the enviro variable method is that it is silently ignored for earlier versions of GRASS. For earlier versions of GRASS an error happens when "--quiet" isn't recognized as a valid command line option. (the new 6.2.3 knows to ignore it)


see "Verbosity levels" on the Development_Specs page.


The advantage of these methods versus sending all stderr to /dev/null is that warning and error messages are not lost, making prototyping and debugging a whole lot easier.


Bash

See the SUBMITTING_SCRIPTS file(s) for some tips.

See the existing GRASS scripts in the scripts/ directory for examples of using tempfiles, etc.

Newer versions of Ubuntu use Dash as the default /bin/sh, so don't assume that sh will handle Bashisms.

Python

Calling modules

Don't use os.system(); use subprocess.Popen() instead. E.g.:

import os
import subprocess
...
proc = subprocess.Popen(["r.mapcalc", "blabla=2*bla"], stdout=file(os.devnull, "w"))
retcode = proc.wait()

This avoids a number of pitfalls with using a shell, including the fact that shell syntax varies widely between platforms.