Sunday 29 November 2015

Processing framework input variables from QGIS-2 not working in QGIS-3


A simple script created within the QGIS 2.18 processing toolbox:


##example=string
print example

Upon running would produce and input box in a window with a run button: enter image description here


Once executed would produce the expected print in the python console


When testing the same code in QGIS-3.0, changing the print to python 3's print(), I get an error where the input section is seemingly ignored as a comment: enter image description here



Does the processing framework no longer accept inputs in this way?



Answer



Seems that the processing script approach is quite different in the QGIS 3.0 than in the QGIS 2.x versions. At least, at the moment the old script syntax has given way to the Pythonic way to implement processing algorithms.


Here is an example processing script that works in QGIS 3.0.0. I took it, including the comments, from the result that Plugin Builder by GeoApt LLC creates for processing:


# -*- coding: utf-8 -*-

from PyQt5.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsProcessingAlgorithm,

QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink)


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'
INPUT = 'INPUT'

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.
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
self.tr('Input layer'),
[QgsProcessing.TypeVectorAnyGeometry]
)
)


# 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')
)
)


def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""

# Retrieve the feature source and sink. The 'dest_id' variable is used
# to uniquely identify the feature sink, and must be included in the
# dictionary returned by the processAlgorithm function.
source = self.parameterAsSource(parameters, self.INPUT, context)

(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
context, source.fields(), source.wkbType(), source.sourceCrs())

# Compute the number of steps to display within the progress bar and
# get features from source
total = 100.0 / source.featureCount() if source.featureCount() else 0
features = source.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))

# Return the results of the algorithm. In this case our only result is

# the feature sink which contains the processed features, but some
# algorithms may return multiple feature sinks, calculated numeric
# statistics, etc. These should all be included in the returned
# dictionary, with keys matching the feature corresponding parameter
# or output names.
return {self.OUTPUT: dest_id}

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 'duplicatevectorlayer'

def displayName(self):
"""
Returns the translated algorithm name, which should be used for any

user-visible display of the algorithm name.
"""
return self.tr('Duplicate a vector layer')

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 tr(self, string):
return QCoreApplication.translate('Processing', string)

def createInstance(self):
return ExampleProcessingAlgorithm()

Please, take a look into this blog post by Anita Graser for more detailed information on how to create a processing script in QGIS 3: Processing script template for QGIS3. Also, there is a GitHub pull request #6678 load default script from template by Matteo Ghetta to ease the processing algorithm script creation in QGIS.


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...