[ create a new paste ] login | about

Link: http://codepad.org/AlDzdVmi    [ raw code | fork ]

Python, pasted on May 21:
# clip_shp_to_shp.py
from qgis.core import *
from qgis.gui import *
import qgis.utils
import os
import glob

CLIP_DIR = 'path to your working directory'
SHP_CLIP = 'path to your clipper shapefile'

class Clipper:
    def __init__(self, iface):
        """Initialize using the qgis.utils.iface
        object passed from the console.
        """
        self.iface = qgis.utils.iface
    
    def clip_shp_to_shp(self, directory, shpclippath, pref="", suf="_clip"):
        # List shp file in a directory (not recursive)
        listResults = glob.glob(os.path.join(directory, '*.shp'))
        # call ogr2ogr to clip with shpclip var
        import subprocess
        for source in listResults:
            subprocess.call(["ogr2ogr", "-f", "ESRI Shapefile", "-clipsrc", shpclippath, os.path.basename(source) + "_clip.shp", source])
    
    def load_shapefiles(self, directory):
        dirClippedShp = glob.glob(os.path.join(directory, '*_clip.shp'))
        print dirClippedShp
        for shp in dirClippedShp:
            (shpdir, shpfile) = os.path.split(shp)
            print "Loading %s" % shpfile
            lyr = QgsVectorLayer(shp, shpfile, 'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(lyr)

def run_script(iface):
    clipper = Clipper(iface)
    clipper.clip_shp_to_shp(CLIP_DIR, SHP_CLIP)
    clipper.load_shapefiles(CLIP_DIR)


Create a new paste based on this one


Comments: