Converting Bash scripts to Python: Difference between revisions

From GRASS-Wiki
Jump to navigation Jump to search
No edit summary
 
(5 intermediate revisions by one other user not shown)
Line 1: Line 1:
This page contains some notes for the users who are converting their Bash script to [[GRASS and Python|Python]].
This page contains some notes for the users who are converting their Bash script to [[GRASS and Python|Python]].
 
__TOC__
== User break ==
== User break ==


Line 37: Line 37:
</source>
</source>


== Discard warning/error messages ==
In Bash:
<source lang=bash>
g.remove rast='map' 2>/dev/null
</source>
In Python:
<source lang=python>
import os
import grass.script as grass
nuldev = file(os.devnull, 'w+')
grass.run_command('g.remove', rast = 'map', stderr = nuldev)
nuldev.close()
</source>
{{Python}}
{{Python}}
Note: In GRASS 6.5+ set
export GRASS_MESSAGE_FORMAT=silent (in Bash)
os.environ['GRASS_MESSAGE_FORMAT'] = 'silent' (in Python)
[[Category:Scripting]]

Latest revision as of 17:44, 2 February 2013

This page contains some notes for the users who are converting their Bash script to Python.

User break

In Bash:

# what to do in case of user break:
exitprocedure()
{
 g.remove rast=$TMP1 > /dev/null
}
# shell check for user break (signal list: trap -l)
trap "exitprocedure" 2 3 15

In Python:

import sys
import atexit

import grass.script as grass

def cleanup():
    grass.run_command('g.remove',
                      rast = tmp1)

def main():
    ...
    return 0

if __name__ == "__main__":
    options, flags = grass.parser()
    atexit.register(cleanup)
    sys.exit(main())

Discard warning/error messages

In Bash:

g.remove rast='map' 2>/dev/null

In Python:

import os
import grass.script as grass

nuldev = file(os.devnull, 'w+')
grass.run_command('g.remove', rast = 'map', stderr = nuldev)
nuldev.close()

Note: In GRASS 6.5+ set

export GRASS_MESSAGE_FORMAT=silent (in Bash)

os.environ['GRASS_MESSAGE_FORMAT'] = 'silent' (in Python)