[GIS] QGIS python processing.runalg Clip returns None

clippyqgispythonqgisqgis-processing

I'm writing a script in pyQGIS, which would emulate measurement of a line by "walking" along it with a compass with constant length. I have a problem with the Clip algorythm from processing module, namely it returns None, regardless of whether I add layers as inputs or selected features. What do I do wrong? I believe, that should the clip result in an empty layer, it would still be there, just empty? Below is the piece of code with problems,

while d.measureLine(QgsPoint(coorFin[0],coorFin[1]),QgsPoint(coor[0],coor[1]))>step: # If the distance between current and last point is more than chosen step
    # Create buffer polygon around a point
    bufCirc = point.geometry().buffer(step,10) # do a buffer from existing point 
    buforek = QgsFeature()
    buforek.setGeometry(bufCirc)

# Create layer and put the polygon inside
    bufferLayer = QgsVectorLayer("Polygon", "temporary_polygons", "memory")
    pz = bufferLayer.dataProvider()
    bufferLayer.setCrs(my_crs)
    pz.addFeatures([buforek])
    bufferLayer.commitChanges()

# select the buffer
    buforSel = bufferLayer.setSelectedFeatures([buforek]) 

# Clip coastline with the buffer
    liniaWarstwa = processing.runandload("qgis:clip", selectedCoastLine, buforSel, "memory:liniaWarstwa")
    print liniaWarstwa
    layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:liniaWarstwa")[0]

The print prints "none", QgsMapLayerRegistry says "index out of range".

Best Answer

Aside of what Joseph mentioned, there is a number of other things you need to keep in mind when clipping from/to memory, so a little check-list for all of you using processing algorithms and memory layers:

  • check, that your version of processing plugin is the newest (2.12.2 behaves in a way described by Joseph), update if not.
  • Make sure all layers are in the same crs, as is your canvas. Have it explicitly set in code.
  • Run your desired algorithm from GUI and check what name does an output have. For example Polish version of QGIS has the output names translated, so I had to put "Przycięte" instead of "Clipped"... Alternatively you can change language to English, which may be safer, to avoid specific characters of your language.
  • Have both clip layers loaded onto canvas (use QgsMapLayerRegistry.instance().addMapLayer(layerIHoldInMemory) )
  • But the most important part of my solution was: Don't use QGIS versions newer than 2.4. It seems, that there is some sort of problem with processing polygons/lines, it works nicely, but on QGIS 2.2 Valmiera.
Related Question