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?

...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.

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:

Gabriel De Luca- thanks, I think that gets me 90% of the way there! (And thanks Francisco Raga- that helps too). Now the issue is that the output folder location I specify in my Processing toolbox options (C:/Users/Nick/.qgis2/processing/output) is not where the output goes. So the dirname I have to delete is always something like C:\Users\Nick\AppData\Local\Temp\processing4abde9e45f184fd1994ba462efffdfb5. But I don't know what the characters will be after \processing. I've tried shutil.rmtree(C:\Users\Nick\AppData\Local\Temp\processing* but python doesn't like that syntax. Ideas?
– Nick_WFeb 2 '19 at 20:08

A step closer, I think- adapted from: stackoverflow.com/questions/185936/…import glob import shutil files = glob.glob('C:\Users\Nick\AppData\Local\Temp\processing*') for f in files: shutil.rmtree(f) It worked in the python console a minute ago. And then when I tried it again it didn't work.
– Nick_WFeb 3 '19 at 1:19