[GIS] Using memory layer for processing algorithms in QGIS 3

memory-layerqgisqgis-3qgis-pluginsqgis-processing

I would like to run a processing algorithms in QGIS3 with a memory vector layer as result.

When I define the memory layer as shown in the following, I get the error

Incorrect parameter value for output

while in the Python Error window output is indicated as QgsVectorLayer and nodesLayer.isValid() returns True:

crs = str(inputLayer.crs().authid())
outputLayer = QgsVectorLayer('Point?crs=' + crs , "points", "memory")
processing.run('grass7:v.net',
                {"input":inputLayer,
                 ...
                "output": outputLayer})

If I use a path to the output layer, everything works fine:

outputLayer = r"path_to_file\output.shp"
processing.run('grass7:v.net',
                {"input":inputLayer,
                 ...
                "output": outputLayer})

Any idea on how to correctly create a memory layer in QGIS 3?

Best Answer

As Germán noted, you should use "memory:" as the output string. But you'll also need to store the algorithm results, or the memory layer will be garbage collected by python!

results = processing.run('grass7:v.net',
            {"input":inputLayer,
             ...
            "output": 'memory:'})
result_layer = results['output']

But more generally - it's a bit inefficient to use a memory layer here. Because you're calling a grass algorithm (not a native QGIS one), all the outputs and inputs are being converted to disk based formats for use by grass, and all outputs from grass are also disk-based (behind the scenes these are shapefiles in a temporary directory). So when you ask for a memory layer output, QGIS has to read over the shapefile created by grass and convert that to a QGIS memory layer. So in this case, it's actually more efficient to just give the algorithm a path to save the shapefile and then read that directly.