QGIS Memory Output – How to Load Memory Output from QGIS Processing

memorypyqgisqgisqgis-processingsextante

Many processing algorithms have an option to save output as memory. If ran from toolbox, this works fine, because you can tick the "Open output file after running algorithm" box.

Looking at the source code for QGIS, the code for loading the memory layer seems to be defined in the function Postprocessing.handleAlgorithmResults. The function uses access to an alg.outputs list, and does the following:

for out in alg.outputs:
    progress.setPercentage(100 * i / float(len(alg.outputs)))
    if out.hidden or not out.open:
        continue
    if isinstance(out, (OutputRaster, OutputVector, OutputTable)):
        try:
            if out.value.startswith('memory:'):
                layer = out.memoryLayer                                # NOTE!!
                QgsMapLayerRegistry.instance().addMapLayers([layer])   # NOTE!!
            else:
                # ... 

When you run processing algorithms from the console, is there a way to load the layer without access to this object? I can run

processing.runalg("qgis:intersection", layer1, layer2, "memory:")

or even

processing.runalg("qgis:intersection", layer1, layer2, "memory:myLayerName")

I can however not find a way to grab the resulting output.

Best Answer

Aaaand I found it. Use processing.runandload, which loads the output layer into the table of contents after running the algorithm.

processing.runandload("qgis:intersection", layer1, layer2, "memory:myLayerName")
layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:myLayerName")[0]
# Should do error checking as well, but this works!!