db.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. @package grass.script.db
  3. @brief GRASS Python scripting module
  4. Database related functions to be used in Python scripts.
  5. Usage:
  6. @code
  7. from grass.script import core, db as grass
  8. grass.parser()
  9. grass.db_describe(table)
  10. ...
  11. @endcode
  12. (C) 2008-2009 by the GRASS Development Team
  13. This program is free software under the GNU General Public
  14. License (>=v2). Read the file COPYING that comes with GRASS
  15. for details.
  16. @author Glynn Clements
  17. @author Martin Landa <landa.martin gmail.com>
  18. """
  19. from core import *
  20. def db_describe(table, **args):
  21. """Return the list of columns for a database table
  22. (interface to `db.describe -c').
  23. @param table table name
  24. @param args
  25. @return parsed module output
  26. """
  27. s = read_command('db.describe', flags = 'c', table = table, **args)
  28. if not s:
  29. return None
  30. cols = []
  31. result = {}
  32. for l in s.splitlines():
  33. f = l.split(':')
  34. key = f[0]
  35. f[1] = f[1].lstrip(' ')
  36. if key.startswith('Column '):
  37. n = int(key.split(' ')[1])
  38. cols.insert(n, f[1:])
  39. elif key in ['ncols', 'nrows']:
  40. result[key] = int(f[1])
  41. else:
  42. result[key] = f[1:]
  43. result['cols'] = cols
  44. return result
  45. # run "db.connect -p" and parse output
  46. def db_connection():
  47. """Return the current database connection parameters
  48. (interface to `db.connect -p').
  49. """
  50. s = read_command('db.connect', flags = 'p')
  51. return parse_key_val(s, sep = ':')