问题描述
我需要为我的QGIS项目加载几个矢量层,以便在其中每个脚本中测试脚本的每个功能。但是,最后,我只希望处理一个或两个感兴趣的图层,而丢弃其他感兴趣的图层,所以我想自动执行此操作。
我成功地完成了一些工作,但是有一层导致了我的问题,但我还没有弄清楚为什么。
这是一些代码:
正在加载图层(肯定不是几乎的问题):
a2 = iface.addVectorLayer(path + ardida2,"","ogr")
if not a2:
print("Layer Failed to load!")
a3 = iface.addVectorLayer(path + ardida3,"ogr")
if not a3:
print("Layer Failed to load!")
现在这是我创建的用于删除除我要使用的图层之外的所有已加载图层的函数。 prints
只是因为我试图理解问题。
def RemoveAllLayersExcept(*layers):
layer_ids = []
for l in layers:
layer_ids.append(l.id())
print('layer_ids',layer_ids)
for lyr in QgsProject.instance().mapLayers():
print(lyr)
if lyr not in layer_ids:
print('not')
QgsProject.instance().removeMapLayer(lyr)
else:
pass
然后,我创建了一个新层-导致我出现问题的那一层。稍后,我需要在迭代过程中编辑此层。我按照OpenSourceOptions教程中名为PyQGIS: Create a Shapefile的分步示例进行操作:
# OPENSOURCEOPTIONS TUTORIAL - PYQGIS: Create a Shapefile
# create fields
layerFields = QgsFields()
layerFields.append(QgsField('ID',QVariant.Int))
layerFields.append(QgsField('Value',QVariant.Double))
layerFields.append(QgsField('Name',QVariant.String))
# Now define the file path for the new shapefile
# Note: the CRS used here is NAD 1983 UTM Zone 11 N
fn = 'D:/Sara/Trabalho/QGIS/pnogas/fireball_points.shp'
writer = QgsvectorFileWriter(fn,'UTF-8',layerFields,QgsWkbTypes.Point,QgsCoordinateReferenceSystem('epsg:26912'),'ESRI Shapefile')
# For each feature we need to set the geometry (in this case a point)
# set the attribute values,then add it to the vector layer.
feat = QgsFeature() # create an empty QgsFeature()
feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(cx14,cy14))) # create a point and use it to set the feature geometry
feat.setAttributes([1,1.1,'one']) # set the attribute values
writer.addFeature(feat) # add the feature to the layer
layer_fireball = iface.addVectorLayer(fn,'','ogr')
if not layer_fireball:
print("Layer Failed to load!")
del(writer)
然后我删除这些图层,这些对我不感兴趣:
RemoveAllLayersExcept(layer,layer_fireball)
就是这样。当我第一次运行该程序时,没有任何反应。这就是我得到的:
layer_ids ['COS2018_ardida2018_3_clip_cbf56f4b_e668_4c2e_9259_7d22d5943097','fireball_points_f92b32e0_f8bf_42c1_95e6_b317ddf6ee84']
COS2018_ardida2018_2_clip_45b241c4_fb9b_4654_9916_5ff08514c559
not
COS2018_ardida2018_3_clip_cbf56f4b_e668_4c2e_9259_7d22d5943097
fireball_points_f92b32e0_f8bf_42c1_95e6_b317ddf6ee84
这符合我的期望。但是在第二和第n次,我得到了:
Layer Failed to load!
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS3~1.10\apps\python37\lib\code.py",line 90,in runcode
exec(code,self.locals)
File "<input>",line 1,in <module>
File "<string>",line 676,line 104,in RemoveAllLayersExcept
AttributeError: 'nonetype' object has no attribute 'id'
您能检测出问题出在哪里吗?为什么会出现此错误?为什么只从第二次开始就发生呢?
谢谢!
解决方法
更改pip install tensorflow==1.15.0
方法,如下所示:
RemoveAllLayersExcept