I've been cobbling together some Processing scripts for QGIS 2.18 (I'm not a fan of QGIS 3 scripts), and I keep running into one particular problem: my script creates a lot of scratch layers and they stick around until I reboot QGIS.
Question: How can I get rid of all the invisible scratch layers after running a script?
For example, running the following:
...creates a point shapefile at
C:\Users\Nick\AppData\Local\Temp\processing7a722160fed94f10b2cfe8e4dac9e9f8\18f2cf1c3459481b9d1f75d8e1b04a5b\POINTS.shp , which can be called with
outputs_SAGACONVERTLINESTOPOINTS_1['POINTS'] in later lines of the script. The file stays there until I exit and restart QGIS. I would like to clear out that file (and the rest that my script generates but does not load into the main layer tree) when the script finishes running.
Digging around a bit, it looks like the QGIS manual almost gets me there with pre/post execution hooks: https://docs.qgis.org/2.18/en/docs/training_manual/processing/hooks.html
import os import shutil from processing.core.outputs import OutputVector, OutputRaster, OutputFile MY_DIRECTORY = '/home/alex/outputs' for output in alg.outputs: if isinstance(output, (OutputVector, OutputRaster, OutputFile)): dirname = os.path.split(output.value) shutil.copytree(dirname, MY_DIRECTORY)
Except that the example does exactly the opposite of what I want. How could that script hook be modified to clear out the junk "ghost layers" (or whatever the correct term is for the layers that are created but not loaded into the Layers Panel) and leave me with a fresh scratch file location before running the next script?
If there's an alternative method for clearing the cached "ghost layers" that's better (and easy for a Python neophyte), I'd be interested in that as well. Any ideas?
Edit (2019-03-10): Minor progress. The following works, run from the python console, but not as a post-execution hook:
import glob import shutil files = glob.glob('C:\Users\UserName\AppData\Local\Temp\processing*') for f in files: shutil.rmtree(f)
NOTE: All of the temporary/scratch layers must be removed from the QGIS layer tree for this to work.