script_intro.rst 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. GRASS GIS Python scripting with script package
  2. ==============================================
  3. Parts of the API
  4. ----------------
  5. .. toctree::
  6. :maxdepth: 2
  7. script
  8. Syntax
  9. ------
  10. First, try a standard command in Command console in Layer Manager::
  11. r.info map=elevation -g
  12. We are running *r.info* with an option ``map`` set to ``elevation`` Now,
  13. switch to Python shell and type the same command but in Python syntax::
  14. grass.read_command('r.info', map='elevation', flags='g')
  15. We used function ``read_command()`` from the ``grass.script`` package
  16. which is imported under the name ``grass`` in the Python shell in GRASS
  17. GUI. There are also other functions besides ``read_command()`` most
  18. notably ``run_command()``, ``write_command()`` and ``parse_command()``.
  19. The first parameter for functions from this group is the name of the
  20. GRASS module as string. Other parameters are options of the module.
  21. Python keyword arguments syntax is used for the options. Flags can be
  22. passed in a parameter ``flags`` where value of the parameter is a string
  23. containing all the flags we want to set. The general syntax is the
  24. following::
  25. function_name('module.name', option1=value1, option2=..., flags='flagletters')
  26. The function parameters are the same as module options, so you can just
  27. use standard module manual page to learn about the interface.
  28. Most of the GRASS functionality is available through modules and all of
  29. them can be called using the functions above. However, in some cases, it
  30. is more advantageous to use specialized Python functions. This is the
  31. case for ``mapcalc()`` function (wrapper for *r.mapcalc* module) and
  32. ``list_strings()`` function (wrapper for *g.list* module).
  33. Combining multiple modules
  34. --------------------------
  35. To launch a Python script from GUI, use File -> Launch Python script.
  36. ::
  37. import grass.script as gscript
  38. def main():
  39. input_raster = 'elevation'
  40. output_raster = 'high_areas'
  41. stats = gscript.parse_command('r.univar', map='elevation', flags='g')
  42. raster_mean = float(stats['mean'])
  43. raster_stddev = float(stats['stddev'])
  44. raster_high = raster_mean + raster_stddev
  45. gscript.mapcalc('{r} = {a} > {m}'.format(r=output_raster, a=input_raster,
  46. m=raster_high))
  47. if __name__ == "__main__":
  48. main()
  49. Processing many maps
  50. --------------------
  51. ::
  52. import grass.script as gscript
  53. def main():
  54. rasters = ['lsat7_2002_10', 'lsat7_2002_20', 'lsat7_2002_30', 'lsat7_2002_40']
  55. max_min = None
  56. for raster in rasters:
  57. stats = gscript.parse_command('r.univar', map=raster, flags='g')
  58. if max_min is None or max_min < stats['min']:
  59. max_min = stats['min']
  60. print max_min
  61. if __name__ == "__main__":
  62. main()
  63. Providing GRASS module interface to a script
  64. ---------------------------------------------
  65. ::
  66. #!/usr/bin/env python
  67. #%module
  68. #% description: Adds the values of two rasters (A + B)
  69. #% keyword: raster
  70. #% keyword: algebra
  71. #% keyword: sum
  72. #%end
  73. #%option G_OPT_R_INPUT
  74. #% key: araster
  75. #% description: Name of input raster A in an expression A + B
  76. #%end
  77. #%option G_OPT_R_INPUT
  78. #% key: braster
  79. #% description: Name of input raster B in an expression A + B
  80. #%end
  81. #%option G_OPT_R_OUTPUT
  82. #%end
  83. import sys
  84. import grass.script as gscript
  85. def main():
  86. options, flags = gscript.parser()
  87. araster = options['araster']
  88. braster = options['braster']
  89. output = options['output']
  90. gscript.mapcalc('{r} = {a} + {b}'.format(r=output, a=araster, b=braster))
  91. return 0
  92. if __name__ == "__main__":
  93. sys.exit(main())
  94. The options which has something like ``G_OPT_R_INPUT`` after the word
  95. ``option`` are called standard options. Their list is accessible
  96. in GRASS GIS `C API documentation`_ of ``STD_OPT`` enum from ``gis.h`` file.
  97. Always use standard options if possible. They are not only easier to use
  98. but also ensure consistency across the modules and easier maintanenace
  99. in case of updates to the parameters parsing system.
  100. Typically, you change ``description`` (and/or ``label``), sometimes ``key``
  101. and ``answer``. There are also standard flags to be used
  102. with ``flag`` which work in the same way.
  103. The examples of syntax of options and flags (without the ``G_OPT...`` part)
  104. can be obtained from any GRASS module using special ``--script`` flag.
  105. Alternatively, you can use GRASS source code to look how different scripts
  106. actually define and use their parameters.
  107. Note that the previous code samples were missing some whitespace which
  108. Python PEP8 style guide requires but this last sample fulfills all the
  109. requirements. You should always use *pep8* tool to check your syntax and
  110. style or set your editor to do it for you. Note also that although
  111. a some mistakes in Python code can be discovered only when executing
  112. the code due to the dynamic nature of Python, there is a large number
  113. of tools such as *pep8* or *pylint* which can help you to identify problems
  114. in you Python code.
  115. .. _C API documentation: http://grass.osgeo.org/programming7/gis_8h.html