Releasing PyQGIS file locks?
Sorry to keep answering my own questions, but I think I found a solution.
As it turns out, it works well if you add the layer to the map registry, and then remove it again. The map registry takes ownership of the layer, so when it is deleted from the registry, the locks are freed. Note that you have to add the layer to the legend (.addMapLayer(layer, addToLegend = False
) won't work).
Still not sure whether to call this a solution or a workaround, but it does the job.
# ...
# Replace the following code (note: should do error checking on map registry functions):
# Load layer 1
layer1 = QgsVectorLayer(layer1_path, "lyr1", "ogr")
if not layer1.isValid(): raise Exception("Failed to load layer 1")
QgsMapLayerRegistry.instance().addMapLayer(layer1) #!!!!
# Use layer 1 to create layer 2
processing.runalg("qgis:reprojectlayer", layer1, "EPSG:54030", layer2_path)
# Load layer 2
layer2 = QgsVectorLayer(layer2_path, "lyr2", "ogr")
if not layer2.isValid(): raise Exception("Failed to load layer 2")
QgsMapLayerRegistry.instance().addMapLayer(layer2) #!!!!
# Remove layer references
QgsMapLayerRegistry.instance().removeMapLayer(layer1.id()) #!!!!
QgsMapLayerRegistry.instance().removeMapLayer(layer2.id()) #!!!!
# Remove data sources for layers
for f in os.listdir(project_temp_dir):
if f.endswith(".shp") and not os.path.isdir(project_temp_dir + f):
# ...
If anyone has more info, I'd be happy to learn more about this.