Saturday, 7 October 2017

pyqgis - Using QgsExpression.evaluate() on vector layer closes QGIS


I am trying to import a csv layer and run QgsExpression.evaluate() to make some computations on existing columns. However, QGIS 2.18, 3.2, and 3.3 all close when it reaches that point.


    layer.startEditing()

context = QgsExpressionContext()
scope = QgsExpressionContextScope()

exp = QgsExpression(expression)
if exp.hasParserError():
raise Exception(exp.parserErrorString())


for f in layer.getFeatures():
QApplication.processEvents()
scope.setFeature(f)
context.appendScope(scope)

value = exp.evaluate(context)

computed_values[field_name].append(value)


f.setAttribute(f.fieldNameIndex(field_name), value)

layer.updateFeature(f)

layer.commitChanges()

Is there any way to make it work for shapefile, or just ogr table layer?



Answer



Don't append the scope inside your loop, do it once outside the loop. Appending the scope transfers ownership of it to the context, and re-appending on the next iteration of the loop will cause undefined behaviour.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...