2

Encountering this weird bug. I'm using QGIS 3.4.7. I am trying to write a script but it crashes when I run it from the editor. But it does not crash when run from the Processing Toolbox. Right now the script does not do anything yet. It just takes an input and outputs it.

Sometimes, instead of crashing, I get this Python error

Traceback (most recent call last):
File "C:/OSGEO4~1/apps/qgis-ltr/./python/plugins\processing\gui\AlgorithmDialog.py", line 247, in on_complete
self.feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time))
NameError: free variable 'self' referenced before assignment in enclosing scope

Edited to include code. I didn't include it before because the code is just a copy of the template and it just outputs the same input layer.

def processAlgorithm(self, parameters, context, feedback):
    lpi_lyr = self.parameterAsSource(
        parameters,
        self.INPUT,
        context
    )
    if lpi_lyr is None:
        raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))

    feedback.pushInfo('CRS is {}'.format(lpi_lyr.sourceCrs().authid()))

    count = lpi_lyr.featureCount()
    total = 100.0 / count if count else 0

    feats = [feat for feat in lpi_lyr.getFeatures()]
    feedback.pushInfo('Total number of features: {}'.format(len(feats)))     



    #PROCESSING
    mem_lyr = QgsVectorLayer("Point?crs="+lpi_lyr.sourceCrs().authid(), 'point', 'memory') 
    prov = mem_lyr.dataProvider()
    prov.addAttributes([field for field in lpi_lyr.fields()]) 
    mem_lyr.updateFields()
    prov.addFeatures(feats)  

    ###OUTPUT
    output_lyr = lpi_lyr
    (sink, dest_id) = self.parameterAsSink(
        parameters,
        self.OUTPUT,
        context,
        output_lyr.fields(),
        output_lyr.wkbType(),
        output_lyr.sourceCrs()
    )   

    if sink is None:
        raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))           

    features = output_lyr.getFeatures()

    for current, feature in enumerate(features):
        # Stop the algorithm if cancel button has been clicked
        if feedback.isCanceled():
            break
        # Add a feature in the sink
        sink.addFeature(feature, QgsFeatureSink.FastInsert)
        # Update the progress bar
        feedback.setProgress(int(current * total))  

    feedback.pushInfo('Finished writing sink')

    return {self.OUTPUT: dest_id}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.