[GRASS-user] Accessing GRASS databases from Python

Hi grass-users,

I'd like to find out what is the best way of accessing a pre-connected database in GRASS from a Python script. I can see a few different possible approaches to this, but I'm not sure which to take. Ultimately, I want to be able to do two different tasks:

1) Change data for a row, or rows, in one column based on the values of other columns in the same row(s). Similar to v.db.update qcolumn=???, but I'd like to do the calculations in Python so I have a bit more freedom (accessing existing functions, etc).

2) Calculate statistics based on the content of all, or some (based on an SQL where statement), of the rows from a column in a table. For (a very simplistic) example, calculate the mean from a list of values in a 'temperature' column.

What is the best way to get this information into a manageable form in Python?

I'm running GRASS 6.4.1RC1 on OS X, as compiled by: http://www.kyngchaos.com/

If I could guarantee the database would be in a certain format (DBF, SQLite, etc) I could just use Pythons respective libraries, but that doesn't seem very portable. I've had a look at the database functions in the grass.script.db python library, but haven't had any luck getting the db_select function to work. In the default install, the function didn't even exist in db.py. I've added it, based on the current source, but all I get out is:

>>> grass.script.db.db_select('Population_Density','select * from Population_Density')
Sorry, <output> is not a valid parameter

Any wisdom would be appreciated.

Josh.

Joshua Arnott wrote:

I've had a look at the database functions in
the grass.script.db python library, but haven't had any luck getting the
db_select function to work. In the default install, the function didn't
even exist in db.py. I've added it, based on the current source, but all
I get out is:

>>> grass.script.db.db_select('Population_Density','select * from
Population_Density')
Sorry, <output> is not a valid parameter

That parameter was added in 7.0. The 6.x version of db.select always
writes to stdout.

You can just run db.select using grass.script.pipe_command(), e.g.:

  import grass.script as grass

  ps = grass.pipe_command(
      'db.select',
      quiet = True,
      flags = 'c',
      table = table,
      sql = sql)

  for line in ps.stdout:
      fields = line.strip().split('|')
      ...

  ps.wait()

--
Glynn Clements <glynn@gclements.plus.com>