1

I'm writing some scripts on QGIS Python console, and I would like to implement some dialog windows, as those about the parameters' insertment, converting from the result of model builder, but when I copy and paste the script on console, this doesn't work.

How can I solve this problem?

Here the code of an example script from the modeler.



from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterVectorLayer
from qgis.core import QgsProcessingParameterNumber
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsExpression
from qgis.core import QgsVectorLayer
from qgis.core import QgsFeatureRequest
import processing


class Modello(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterVectorLayer('comuneselezionato', 'ComuneSelezionato', types=[QgsProcessing.TypeVectorPolygon], defaultValue=None))
        self.addParameter(QgsProcessingParameterNumber('intensit_terremoto', 'Intensità Terremoto', optional=True, type=QgsProcessingParameterNumber.Double, minValue=3, maxValue=12, defaultValue=None))
        self.addParameter(QgsProcessingParameterNumber('distanza_dallepicentro', "Distanza dall'epicentro", type=QgsProcessingParameterNumber.Integer, minValue=15000, maxValue=200000, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Evidenziaedifici', 'EvidenziaEdifici', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(4, model_feedback)
        results = {}
        outputs = {}

        # Ritaglia
        alg_params = {
            'INPUT': 'Edifici_filtrati_per_datazione_d5f42b62_efc8_483a_b355_e6013129b596',
            'OVERLAY': parameters['comuneselezionato'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Ritaglia'] = processing.run('native:clip', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Centroidi
        alg_params = {
            'ALL_PARTS': False,
            'INPUT': 'IsosismeTerremotiTotaliA200KmDaToscanaELiguria_b2371c3b_9244_4008_b848_a3a55fbd7353',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        layerTerremoti = QgsVectorLayer("alg_params['INPUT']", "terremoti", "ogr")
        intensitaTerr = parameters['intensit_terremoto']
        
        if feedback.isCanceled():
            return {}

        # Buffer
        alg_params = {
            'DISSOLVE': False,
            'DISTANCE': QgsExpression(' @distanza_dallepicentro ').evaluate(),
            'END_CAP_STYLE': 0,  # Arrotondato
            'INPUT': outputs['Centroidi']['OUTPUT'],
            'JOIN_STYLE': 0,  # Arrotondato
            'MITER_LIMIT': 2,
            'SEGMENTS': 5,
            'SEPARATE_DISJOINT': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Buffer'] = processing.run('native:buffer', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        # Estrai per posizione
        alg_params = {
            'INPUT': outputs['Buffer']['OUTPUT'],
            'INTERSECT': outputs['Ritaglia']['OUTPUT'],
            'PREDICATE': [0],  # interseca
            'OUTPUT': parameters['Evidenziaedifici']
        }
        outputs['EstraiPerPosizione'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Evidenziaedifici'] = outputs['EstraiPerPosizione']['OUTPUT']
        return results

    def name(self):
        return 'modello'

    def displayName(self):
        return 'modello'

    def group(self):
        return ''

    def groupId(self):
        return ''

    def createInstance(self):
        return Modello()
2
  • 1
    This is a processing algorithm script. You can run it from the processing script editor for testing, but the idea of processing scripts is that they are added to the processing toolbox via the Python icon in the toolbar of the processing toolbox dockwidget, or packaged into a processing plugin. They are not intended to be run from the Python console.
    – Ben W
    Commented Jul 27 at 11:00
  • So, I can't cut the part that I'm interested in and to paste it in my script written on console? Commented Jul 27 at 11:19

1 Answer 1

1

As was highlighted by @BenW your Python code is a processing algorithm script, that was probably created from a QGIS Model exported as a Python script, see the QGIS Documentation | Exporting a model as a Python script.

I do not know if there is an automatic way to convert this processing algorithm script to a processing Python script, but you can give a try to a manual approach.

By the way one can run the processing algorithm script via:

import processing
from qgis.core import QgsProject

layer = QgsProject.instance().mapLayersByName('POLYGON_LAYER_NAME')[0]

processing.runAndLoadResults("script:modello", {
    'comuneselezionato': layer,
    'intensit_terremoto': 3,
    'distanza_dallepicentro': 15000,
    'Evidenziaedifici': 'TEMPORARY_OUTPUT'
})

References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.