[QGIS-Developer] [Info][Howto] Python Processing script to create an output without input

João Gaspar joao.f.r.gaspar at gmail.com
Wed Jul 31 08:30:15 PDT 2019


Hi devs
I'm trying to do a Python Script in Processing without an input layer and
generate an output layer based on a number of fields that respects an
order, name, type of field, precision.

The problem: I have some standard procedures that use a template shapefile.
Most of the time users create a new template or truncate existing layers.

To save some clicks what I'm trying to do is create instantly the templates
without user lose time. I'm using processing to get the advantage of batch
mode.

This is my actual code but crashes when I run (see .py in attach)

I think the problem is in the moment of writing the output file.

Kind regards
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20190731/84fb052e/attachment-0001.html>
-------------- next part --------------
# -*- coding: utf-8 -*-

"""
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

from PyQt5.QtCore import (QCoreApplication, QVariant)
from qgis.utils import iface 
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSink,
                       QgsFields,
                       QgsField,
                       QgsVectorFileWriter,
                       QgsWkbTypes,
                       QgsCoordinateReferenceSystem,
                       QgsVectorLayer
                       )
import processing


class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
    """
    This is an example algorithm that takes a vector layer and
    creates a new identical one.

    It is meant to be used as an example of how to create your own
    algorithms and explain methods and variables used to do it. An
    algorithm like this will be available in all elements, and there
    is not need for additional work.

    All Processing algorithms should extend the QgsProcessingAlgorithm
    class.
    """

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    OUTPUT = 'OUTPUT'

    def tr(self, string):
        """
        Returns a translatable string with the self.tr() function.
        """
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return ExampleProcessingAlgorithm()

    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'myscript'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr('My Script')

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr('Example scripts')

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'examplescripts'

    def shortHelpString(self):
        """
        Returns a localised short helper string for the algorithm. This string
        should provide a basic description about what the algorithm does and the
        parameters and outputs associated with it..
        """
        return self.tr("Example algorithm short description")

    def initAlgorithm(self, config=None):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # We add the input vector features source. It can have any kind of
        # geometry.

        # We add a feature sink in which to store our processed features (this
        # usually takes the form of a newly created vector layer when the
        # algorithm is run in QGIS).
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr('Output layer'),
                QgsProcessing.TypeVectorPolygon
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        fields = QgsFields()
        fields.append(QgsField("codprop", QVariant.String,'varchar',100))
        fields.append(QgsField("nickname", QVariant.String,'varchar',100))
        fields.append(QgsField("name", QVariant.String,'varchar',35))
        fields.append(QgsField("area", QVariant.Double,'double',9,4))
        fields.append(QgsField("ao", QVariant.String,'varchar',2))
        fields.append(QgsField("oao", QVariant.String,'varchar',3))
        fields.append(QgsField("arm", QVariant.String,'varchar',1))
        writer= QgsVectorFileWriter(self.OUTPUT, "UTF8", fields, QgsWkbTypes.MultiPolygon, QgsCoordinateReferenceSystem("EPSG:3763"), "ESRI Shapefile")
        layer = iface.addVectorLayer(self.OUTPUT, 'layer1', 'ogr')        
        return {self.OUTPUT: layer}


More information about the QGIS-Developer mailing list