我想知道是什么触发了pyQGIS中文件锁定的释放?
我试图通过调用删除一些数据源(临时使用)QgsVectorFileWriter.deleteShapeFile
,但是必须退出QGIS才能这样做。我已经将源代码加载到QgsVectorLayer对象中。在删除源之前,是否必须对所有这些对象及其引用进行垃圾回收?有没有办法强制执行此操作?
我设法创建了一个失败的最小代码示例。在运行之前,请确保temp目录为空。
from qgis.core import *
import processing, os, gc
project_temp_dir = "C:/Path/To/My/Dir/"
layer1_path = project_temp_dir + "layer1.shp"
layer2_path = project_temp_dir + "layer2.shp"
input_layer = QgsMapLayerRegistry.instance().mapLayersByName('in_layer')[0]
if not input_layer.isValid(): raise Exception("Failed to grab input layer")
# Create layer 1
err = QgsVectorFileWriter.writeAsVectorFormat(input_layer, layer1_path, "utf-8", input_layer.crs())
if err != QgsVectorFileWriter.NoError: raise Exception("Failed to write layer 1")
# Load layer 1
layer1 = QgsVectorLayer(layer1_path, "lyr1", "ogr")
if not layer1.isValid(): raise Exception("Failed to load layer 1")
# Use layer 1 to create layer 2, read-only makes no difference
# if not layer1.setReadOnly(): raise Exception("Could not set layer 1 to read-only")
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")
del layer1
del layer2
del input_layer
gc.collect()
print "Garbage: " + str(gc.garbage) # Empty
# Remove data sources for layers - FAILS!!
for f in os.listdir(project_temp_dir):
if f.endswith(".shp") and not os.path.isdir(project_temp_dir + f):
if not QgsVectorFileWriter.deleteShapeFile(project_temp_dir + f):
# F*%&ing locks.
print "Failed to clear project temp directory."
我发现,如果我使用QgsVectorFileWriter
create layer2
而不是处理算法,它将起作用。如果尝试该qgis:clip
算法,则会收到相同的错误。那么这是处理中的错误吗?我使用错了吗?