3

Writing scripts in previous versions of QGIS, I would get the layer path to pass to algorithms using processing.getObject(layer). In QGIS 3, the scripting system has been rewritten, and I now define a 'source' for input layers like this:

SPECIES_POINTS = 'SPECIES_POINTS'      # INPUT = 'INPUT'

[...]

speciesPointSource = self.parameterAsSource(
            parameters,
            self.SPECIES_POINTS,
            context
        )

I then try to pass it to an algorithm:

pointsReprojected = processing.run("native:reprojectlayer", {
            'INPUT': speciesPointSource,
            'TARGET_CRS': CRS,
            'OUTPUT' : speciesExtent_id
        }, context=context, feedback=feedback)['OUTPUT']

but when I try to run this, I get an error:

Unable to execute algorithm
Could not load source layer for INPUT: invalid value
Traceback (most recent call last):
File "<string>", line 191, in processAlgorithm
File "C:/OSGEO4~1/apps/qgis/./python/plugins\processing\tools\general.py", line 96, in run
return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context)
File "C:/OSGEO4~1/apps/qgis/./python/plugins\processing\core\Processing.py", line 142, in runAlgorithm
raise QgsProcessingException(msg)
_core.QgsProcessingException: Unable to execute algorithm
Could not load source layer for INPUT: invalid value

I can see that speciesPointSource has type QgsFeatureSource, so I'm not surprised this doesn't work, but I can't see any attributes that would give me the file path for the layer. I have also tried self.SPECIES_POINTS but then I get the error Could not load source layer for INPUT: SPECIES_POINTS not found. What should I be passing as 'INPUT'?

5

The input parameters can be accessed as a dictionary object, so parameters['SPECIES_POINTS'] will give you the path to the input layer. The call to the algorithm would then be:

pointsReprojected = processing.run("native:reprojectlayer", {
            'INPUT': parameters['SPECIES_POINTS'],
            'TARGET_CRS': CRS,
            'OUTPUT' : speciesExtent_id
        }, context=context, feedback=feedback)['OUTPUT']

Note that if you are only going to be passing the input object to an algorithm without doing anything with it, it's not necessary to define it as a source. The speciesPointSource = self.parameterAsSource(...) section is not needed.

  • Thank you so much for this. After hours of trying, I figured that must be the only way and landed here to see the confirmation. – spatialthoughts Feb 24 at 13:28

Your Answer

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

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