[Qgis-developer] release file after processing.runalg

enrico chiaradia enrico.chiaradia at yahoo.it
Thu Apr 27 06:13:22 PDT 2017


Dear List,

I'd like to remove an existing file (see [tempOutput]) after it was used 
by a geoalgorithm. The geoalgorithm works perfectly but after its 
execution, the file [tempOutput] is locked.

Here a simple test script that returns "[Error 32] The process cannot 
access the file because it is being used by another process: 
'D:/test_alg/map_to_clip.tif'":

import processing
import os

tempOutput = 'D:/test_alg/map_to_clip.tif'
maskFN = 'D:/test_alg/mask.shp'
output = 'D:/test_alg/clipped_map.tif'

algRes = processing.runalg("gdalogr:cliprasterbymasklayer",
                                         tempOutput,
                                         maskFN,
"-9999",False,False,False,5,4,75,6,1,False,0,False,"",
                                         output)

try:
     os.remove(tempOutput)
except Exception as e:
     print e

I also found a solution on the web [1] but it doesn't work for me :( If 
I understand correctly, the trick is to load the file as layer and then 
release it. Here its implementation:

import processing
import os

tempOutput = 'D:/test_alg/map_to_clip.tif'
maskFN = 'D:/test_alg/mask.shp'
output = 'D:/test_alg/clipped_map.tif'

algRes = processing.runalg("gdalogr:cliprasterbymasklayer",
                                         tempOutput,
                                         maskFN,
"-9999",False,False,False,5,4,75,6,1,False,0,False,"",
                                         output)

try:
     # add to the map
     tempLay = QgsRasterLayer(tempOutput, "tempLay")
     if not tempLay.isValid(): raise Exception("Failed to load tempLay")
     QgsMapLayerRegistry.instance().addMapLayer(tempLay) #!!!!

     layermap = QgsMapLayerRegistry.instance().mapLayers()
     for i, layer in layermap.iteritems():
       print 'layername',layer.source()
       if layer.source() == tempOutput:
         # Remove layer references
         QgsMapLayerRegistry.instance().removeMapLayer(layer.id()) #!!!!
         # Delete the file
         os.remove(tempOutput)

except Exception as e:
     print e

I didn't find any other solution for the moment. Any suggestion is 
really very appreciate!

Thanks

enrico


[1] 
https://gis.stackexchange.com/questions/93143/can-not-delete-file-after-using-runalg-function



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20170427/1cfc159f/attachment.html>


More information about the Qgis-developer mailing list