PyQGIS – Saving Processing Output to Temporary File in QGIS on Windows

pyqgisqgis-3

QGIS 3.10.1, Windows 10:

When using the GDAL tool Clip Vector by Extent from the processing toolbox and saving the output to a temporary file, the output layer appears in the layer list with a special icon (looks like RAM) and the information: "Temporary layer only! Contents will be discarded after closing QGIS":

Temporary output layer

Is it possible to create such a tempory layer also on Windows when using the tool in PyQGIS?

On Linux this is possible, just save the output to /tmp/.

However on Windows, saving the output to the Windows Temp folder (.../AppData/local/Temp/), the created output is not discarded after closing QGIS.

Here is the code I'm using in PyQGIS:

clipped_layer = processing.run("gdal:clipvectorbyextent", {'INPUT': id, 'EXTENT': canvasExtent, 'OUTPUT': outputFolder + 'Canvas_Clipper.A_' + map.name() + '.gpkg'})

newLayer = QgsVectorLayer(clipped_layer['OUTPUT'], 'A_' + map.name(), 'ogr')
QgsProject.instance().addMapLayer(newLayer, False)
clippedGroup.insertLayer(1, newLayer)

Other answers here on gis.stackexchange are suggesting to use NONE or 'memory:' as output parameter, but this gives an error in PyQGIS. Seems like for GDAL tools there is a need to specify an output path.

When using the tool from the processing toolbox in QGIS, the output is saved to a folder which is prefixed processing_ (see the following screenshot). This folder is discarded when QGIS is closed and I assume this folder is created when starting QGIS (the name of the folder changes for every QGIS session).

Is there a way to use/get the name of this tempory processing_ folder as output folder from PyQGIS when running the GDAL tool or to create such a folder which is automatically discarded when QGIS is closed?

Clip vector by Extent

Best Answer

Use the special value QgsProcessing.TEMPORARY_OUTPUT as the output parameter value, and the rest will all be taken care of for you.

e.g.

clipped_layer = processing.run("gdal:clipvectorbyextent", {'INPUT': id, 'EXTENT': canvasExtent, 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT})['OUTPUT']
Related Question