浏览代码

Python swig and script modules reorganized
grass
grass.lib
grass.lib.*
grass.script
grass.script.core
grass.script.db
grass.script.raster
grass.script.vector


git-svn-id: https://svn.osgeo.org/grass/grass/trunk@37345 15284696-431f-4ddb-bdfa-cd5b030d7da7

Martin Landa 16 年之前
父节点
当前提交
d18aa6d49d
共有 7 个文件被更改,包括 298 次插入162 次删除
  1. 21 5
      lib/python/Makefile
  2. 4 0
      lib/python/__init__.py
  3. 26 150
      lib/python/grass.py
  4. 62 0
      lib/python/db.py
  5. 67 0
      lib/python/raster.py
  6. 105 0
      lib/python/vector.py
  7. 13 7
      swig/python/Makefile

+ 21 - 5
lib/python/Makefile

@@ -3,13 +3,29 @@ MODULE_TOPDIR = ../..
 include $(MODULE_TOPDIR)/include/Make/Other.make
 include $(MODULE_TOPDIR)/include/Make/Doxygen.make
 
-default: $(ETC)/python
-	$(MAKE) $(ETC)/python/grass.py $(ETC)/python/README.txt
+PYDIR = $(ETC)/python
+GDIR = $(PYDIR)/grass
+DSTDIR = $(GDIR)/script
 
-$(ETC)/python:
-	-if [ ! -d $@ ]; then $(MKDIR) $@; fi
+MODULES = grass core db raster vector
 
-$(ETC)/python/%: %
+PYFILES := $(patsubst %,$(DSTDIR)/%.py,$(MODULES) __init__)
+
+default: $(DSTDIR)
+	$(MAKE) $(PYFILES) $(DSTDIR)/README.txt
+
+$(PYDIR):
+	test -d $@ || $(MKDIR) -p $@
+
+$(GDIR): $(PYDIR)
+	test -d $@ || $(MKDIR) -p $@
+
+$(DSTDIR): $(GDIR)
+	test -d $@ || $(MKDIR) -p $@
+	test -f __init__.py || touch $(GDIR)/__init__.py
+	@echo "import script" >> $(GDIR)/__init__.py
+
+$(DSTDIR)/%: %
 	$(INSTALL_DATA) $< $@
 
 #doxygen:

+ 4 - 0
lib/python/__init__.py

@@ -0,0 +1,4 @@
+import core
+import db
+import raster
+import vector

+ 26 - 150
lib/python/grass.py

@@ -1,11 +1,34 @@
+"""
+@package grass.script.core
+
+@brief GRASS Python scripting module
+
+Core functions to be used in Python scripts.
+
+Usage:
+
+@code
+from grass.script import core as grass
+
+grass.parser()
+...
+@endcode
+
+(C) 2008-2009 by the GRASS Development Team
+This program is free software under the GNU General Public
+License (>=v2). Read the file COPYING that comes with GRASS
+for details.
+
+@author Glynn Clements
+@author Martin Landa <landa.martin gmail.com>
+"""
+
 import os
 import sys
 import types
-import subprocess
 import re
 import atexit
-import string
-import types
+import subprocess
 
 # subprocess wrapper that uses shell on Windows
 
@@ -485,152 +508,5 @@ def try_rmdir(path):
     except:
 	pass
 
-# run "v.db.connect -g ..." and parse output
-
-def vector_db(map, **args):
-    """Return the database connection details for a vector map
-    (interface to `v.db.connect -g').
-
-    @param map vector map
-
-    @return dictionary { layer : { 'layer', 'table, 'database', 'driver', 'key' }
-    """
-    s = read_command('v.db.connect', flags = 'g', map = map, fs = ';', **args)
-    result = {}
-    
-    for l in s.splitlines():
-	f = l.split(';')
-	if len(f) != 5:
-	    continue
-        
-        if '/' in f[0]:
-            f1 = f[0].split('/')
-            layer = f1[0]
-            name = f1[1]
-        else:
-            layer = f[0]
-            name = ''
-            
-	result[int(layer)] = {
-            'layer'    : layer,
-            'name'     : name,
-            'table'    : f[1],
-            'key'      : f[2],
-            'database' : f[3],
-            'driver'   : f[4] }
-    
-    return result
-
-def vector_layer_db(map, layer):
-    """Return the database connection details for a vector map layer.
-    If db connection for given layer is not defined, fatal() is called."""
-    try:
-        f = vector_db(map)[int(layer)]
-    except KeyError:
-	grass.fatal("Database connection not defined for layer %s" % layer)
-
-    return f
-
-# run "db.describe -c ..." and parse output
-
-def db_describe(table, **args):
-    """Return the list of columns for a database table
-    (interface to `db.describe -c').
-    """
-    s = read_command('db.describe', flags = 'c', table = table, **args)
-    if not s:
-	return None
-    cols = []
-    result = {}
-    for l in s.splitlines():
-	f = l.split(':')
-	key = f[0]
-	f[1] = f[1].lstrip(' ')
-	if key.startswith('Column '):
-	    n = int(key.split(' ')[1])
-	    cols.insert(n, f[1:])
-	elif key in ['ncols', 'nrows']:
-	    result[key] = int(f[1])
-	else:
-	    result[key] = f[1:]
-    result['cols'] = cols
-    return result
-
-# run "db.connect -p" and parse output
-
-def db_connection():
-    """Return the current database connection parameters
-    (interface to `db.connect -p').
-    """
-    s = read_command('db.connect', flags = 'p')
-    return parse_key_val(s, sep = ':')
-
-# run "v.info -c ..." and parse output
-
-def vector_columns(map, layer = None, **args):
-    """Return a dictionary of the columns for the database table connected to
-    a vector map (interface to `v.info -c').
-    """
-    s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
-    result = {}
-    for line in s.splitlines():
-	f = line.split('|')
-	if len(f) == 2:
-            result[f[1]] = f[0]
-    
-    return result
-
-# add vector history
-
-def vector_history(map):
-    """Set the command history for a vector map to the command used to
-    invoke the script (interface to `v.support').
-    """
-    run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
-
-# run "v.info -t" and parse output
-
-def vector_info_topo(map):
-    """Return information about a vector map (interface to `v.info -t')."""
-    s = read_command('v.info', flags = 't', map = map)
-    return parse_key_val(s, val_type = int)
-    
-# add raster history
-
-def raster_history(map):
-    """Set the command history for a raster map to the command used to
-    invoke the script (interface to `r.support').
-
-    @return True on success
-    @return False on failure
-    """
-    current_mapset = gisenv()['MAPSET']
-    if find_file(name = map)['mapset'] == current_mapset:
-        run_command('r.support', map = map, history = os.environ['CMDLINE'])
-        return True
-    
-    warning("Unable to write history for <%s>. Raster map <%s> not found in current mapset." % (map, map))
-    return False
-
 def float_or_dms(s):
     return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
-
-# run "r.info -rgstmpud ..." and parse output
-
-def raster_info(map):
-    """Return information about a raster map (interface to `r.info')."""
-    s = read_command('r.info', flags = 'rgstmpud', map = map)
-    kv = parse_key_val(s)
-    for k in ['min', 'max', 'north', 'south', 'east', 'west']:
-	kv[k] = float(kv[k])
-    for k in ['nsres', 'ewres']:
-	kv[k] = float_or_dms(kv[k])
-    return kv
-
-# interface to r.mapcalc
-
-def mapcalc(exp, **kwargs):
-    t = string.Template(exp)
-    e = t.substitute(**kwargs)
-    if run_command('r.mapcalc', expression = e) != 0:
-	fatal("An error occurred while running r.mapcalc")

+ 62 - 0
lib/python/db.py

@@ -0,0 +1,62 @@
+"""
+@package grass.script.db
+
+@brief GRASS Python scripting module
+
+Database related functions to be used in Python scripts.
+
+Usage:
+
+@code
+from grass.script import core, db as grass
+
+grass.parser()
+grass.db_describe(table)
+...
+@endcode
+
+(C) 2008-2009 by the GRASS Development Team
+This program is free software under the GNU General Public
+License (>=v2). Read the file COPYING that comes with GRASS
+for details.
+
+@author Glynn Clements
+@author Martin Landa <landa.martin gmail.com>
+"""
+
+from core import *
+
+# run "db.describe -c ..." and parse output
+
+def db_describe(table, **args):
+    """Return the list of columns for a database table
+    (interface to `db.describe -c').
+    """
+    s = read_command('db.describe', flags = 'c', table = table, **args)
+    if not s:
+	return None
+    cols = []
+    result = {}
+    for l in s.splitlines():
+	f = l.split(':')
+	key = f[0]
+	f[1] = f[1].lstrip(' ')
+	if key.startswith('Column '):
+	    n = int(key.split(' ')[1])
+	    cols.insert(n, f[1:])
+	elif key in ['ncols', 'nrows']:
+	    result[key] = int(f[1])
+	else:
+	    result[key] = f[1:]
+    result['cols'] = cols
+    return result
+
+# run "db.connect -p" and parse output
+
+def db_connection():
+    """Return the current database connection parameters
+    (interface to `db.connect -p').
+    """
+    s = read_command('db.connect', flags = 'p')
+    return parse_key_val(s, sep = ':')
+

+ 67 - 0
lib/python/raster.py

@@ -0,0 +1,67 @@
+"""
+@package grass.script.raster
+
+@brief GRASS Python scripting module
+
+Raster related functions to be used in Python scripts.
+
+Usage:
+
+@code
+from grass.script import core, raster as grass
+
+grass.parser()
+grass.raster_history(map)
+...
+@endcode
+
+(C) 2008-2009 by the GRASS Development Team
+This program is free software under the GNU General Public
+License (>=v2). Read the file COPYING that comes with GRASS
+for details.
+
+@author Glynn Clements
+@author Martin Landa <landa.martin gmail.com>
+"""
+
+import os
+import string
+
+from core import *
+
+# add raster history
+
+def raster_history(map):
+    """Set the command history for a raster map to the command used to
+    invoke the script (interface to `r.support').
+
+    @return True on success
+    @return False on failure
+    """
+    current_mapset = gisenv()['MAPSET']
+    if find_file(name = map)['mapset'] == current_mapset:
+        run_command('r.support', map = map, history = os.environ['CMDLINE'])
+        return True
+    
+    warning("Unable to write history for <%s>. Raster map <%s> not found in current mapset." % (map, map))
+    return False
+
+# run "r.info -rgstmpud ..." and parse output
+
+def raster_info(map):
+    """Return information about a raster map (interface to `r.info')."""
+    s = read_command('r.info', flags = 'rgstmpud', map = map)
+    kv = parse_key_val(s)
+    for k in ['min', 'max', 'north', 'south', 'east', 'west']:
+	kv[k] = float(kv[k])
+    for k in ['nsres', 'ewres']:
+	kv[k] = float_or_dms(kv[k])
+    return kv
+
+# interface to r.mapcalc
+
+def mapcalc(exp, **kwargs):
+    t = string.Template(exp)
+    e = t.substitute(**kwargs)
+    if run_command('r.mapcalc', expression = e) != 0:
+	fatal("An error occurred while running r.mapcalc")

+ 105 - 0
lib/python/vector.py

@@ -0,0 +1,105 @@
+"""
+@package grass.script.vector
+
+@brief GRASS Python scripting module
+
+Vector related functions to be used in Python scripts.
+
+Usage:
+
+@code
+from grass.script import core, vector as grass
+
+grass.parser()
+grass.vector_db(map)
+...
+@endcode
+
+(C) 2008-2009 by the GRASS Development Team
+This program is free software under the GNU General Public
+License (>=v2). Read the file COPYING that comes with GRASS
+for details.
+
+@author Glynn Clements
+@author Martin Landa <landa.martin gmail.com>
+"""
+
+import os
+
+from core import *
+
+# run "v.db.connect -g ..." and parse output
+
+def vector_db(map, **args):
+    """Return the database connection details for a vector map
+    (interface to `v.db.connect -g').
+
+    @param map vector map
+
+    @return dictionary { layer : { 'layer', 'table, 'database', 'driver', 'key' }
+    """
+    s = read_command('v.db.connect', flags = 'g', map = map, fs = ';', **args)
+    result = {}
+    
+    for l in s.splitlines():
+	f = l.split(';')
+	if len(f) != 5:
+	    continue
+        
+        if '/' in f[0]:
+            f1 = f[0].split('/')
+            layer = f1[0]
+            name = f1[1]
+        else:
+            layer = f[0]
+            name = ''
+            
+	result[int(layer)] = {
+            'layer'    : layer,
+            'name'     : name,
+            'table'    : f[1],
+            'key'      : f[2],
+            'database' : f[3],
+            'driver'   : f[4] }
+    
+    return result
+
+def vector_layer_db(map, layer):
+    """Return the database connection details for a vector map layer.
+    If db connection for given layer is not defined, fatal() is called."""
+    try:
+        f = vector_db(map)[int(layer)]
+    except KeyError:
+	grass.fatal("Database connection not defined for layer %s" % layer)
+
+    return f
+
+# run "v.info -c ..." and parse output
+
+def vector_columns(map, layer = None, **args):
+    """Return a dictionary of the columns for the database table connected to
+    a vector map (interface to `v.info -c').
+    """
+    s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
+    result = {}
+    for line in s.splitlines():
+	f = line.split('|')
+	if len(f) == 2:
+            result[f[1]] = f[0]
+    
+    return result
+
+# add vector history
+
+def vector_history(map):
+    """Set the command history for a vector map to the command used to
+    invoke the script (interface to `v.support').
+    """
+    run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+
+# run "v.info -t" and parse output
+
+def vector_info_topo(map):
+    """Return information about a vector map (interface to `v.info -t')."""
+    s = read_command('v.info', flags = 't', map = map)
+    return parse_key_val(s, val_type = int)

+ 13 - 7
swig/python/Makefile

@@ -39,28 +39,34 @@ CLEAN_SUBDIRS = NumPtr
 
 include $(MODULE_TOPDIR)/include/Make/Python.make
 
-DSTDIR = $(ARCH_DISTDIR)/etc/python/swig
+PYDIR = $(ETC)/python
+GDIR = $(PYDIR)/grass
+DSTDIR = $(GDIR)/lib
 
 LIBFILES := $(patsubst %,$(DSTDIR)/_%.so,$(MODULES))
 PYFILES  := $(patsubst %,$(DSTDIR)/%.py,$(MODULES) __init__)
-PYCFILES := $(patsubst %,$(DSTDIR)/%.pyc,$(MODULES) __init__)
 
 default:
 	$(MAKE) $(DSTDIR)
-	$(MAKE) $(LIBFILES) $(PYFILES) $(PYCFILES)
+	$(MAKE) $(LIBFILES) $(PYFILES)
 
-$(DSTDIR):
+$(PYDIR):
 	test -d $@ || $(MKDIR) -p $@
 
+$(GDIR): $(PYDIR)
+	test -d $@ || $(MKDIR) -p $@
+
+$(DSTDIR): $(GDIR)
+	test -d $@ || $(MKDIR) -p $@
+	test -f __init__.py || touch $(GDIR)/__init__.py
+	@echo "import lib" >> $(GDIR)/__init__.py
+
 $(DSTDIR)/_%.so: _%.so
 	$(INSTALL) $< $@
 
 $(DSTDIR)/%.py: %.py
 	$(INSTALL_DATA) $< $@
 
-$(DSTDIR)/%.pyc: %.pyc
-	$(INSTALL_DATA) $< $@
-
 numptr:
 	$(MAKE) -C NumPtr