from qgis.core import QgsApplication, QgsField, QgsProject, \ QgsProcessingFeedback, QgsVectorLayer, QgsVectorDataProvider, \ QgsExpressionContext, QgsExpressionContextUtils from qgis.analysis import QgsNativeAlgorithms import processing class ScrubLayer: def __init__(self, qgis_path, layer_path, layer_name): # Set the path to QGIS installation QgsApplication.setPrefixPath(qgis_path, True) # Initialize QGIS application qgs = QgsApplication([], False) qgs.initQgis() self.layer_path = layer_path self.layer_name = layer_name self.layer = self.load_layer() def load_layer(self): the_layer = QgsVectorLayer(self.layer_path, self.layer_name, 'ogr') if not the_layer.isValid(): raise ValueError(f'Failed to load layer {self.layer_name} from {self.layer_path}') else: QgsProject.instance().addMapLayer(the_layer) return the_layer def create_spatial_index(self): QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) create_spatial_index_params = { 'INPUT': self.layer_path, 'OUTPUT': 'Output' } processing.run("native:createspatialindex", create_spatial_index_params) @staticmethod def cleanup(): QgsApplication.exitQgis() if __name__ == '__main__': app_path = 'C:/Program Files/QGIS 3.34.1/apps/qgis' new_path = 'C:/Users/a_adli/PycharmProjects/hydroquebec_archetype_gispy/' \ 'data/test_data/test_input/nrcan_north/nrcan_north.shp' data_layer_name = 'nrcan_north' handle_layer = ScrubLayer(app_path, new_path, data_layer_name) # print(handle_layer.layer.featureCount()) handle_layer.create_spatial_index()