Manage code restart
Sometimes it is good to remove existing layers and clean your QGIS instance before to run the working code (but also read on because it is not perfect):
project = QgsProject.instance() project.removeAllMapLayers() project.clear() iface.mapCanvas().refresh()
Sometimes it is good to delete all persistent variables at the begining of your code to manage the multi-execution of your script (to be able to run it, and re-run it, then re-run it... it can be useful when your work, but keep to read on because it is not perfect):
for g in globals(): del g
OK guys, now the real solution 😃: according your working context, and especially when you create/re-create new layers and/or new directories (with a geo-process for example), it is better to do it in a function (def
), then to run your function in a QTimer.singleShot
, with a little delay (below 200 milliseconds):
... def myGeoProcess(): ... processing.run('qgis:anyGeoProcess', { ... }) ... QTimer.singleShot(200, myGeoProcess) ...
Find a full example in the chapter named Processing: Intersection or Processing: Buffer.