I want to make a script which
- processes some algorithms with multiple layers as inputs
- outputs some results in QGIS project
- then save the layers as zip files in a specified folder
I have not been successful yet but I have found some interesting informations with post processing methods by Ben W and Kadir Şahbaz : Adding output layers of QGIS processing scripts to group using PyQGIS / Table of content abnormally closing after using showAttributeTable (Processing plugin)
from zipfile import ZipFile
from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterVectorLayer
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsProcessingParameterFolderDestination
from qgis.core import QgsProcessingUtils
import processing
class MyClass(QgsProcessingAlgorithm):
# reference to the output layer id
dest_id = {}
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterVectorLayer('path', 'path', types=[QgsProcessing.TypeVectorLine], defaultValue=None))
self.addParameter(QgsProcessingParameterVectorLayer('point', 'point', types=[QgsProcessing.TypeVectorPoint], defaultValue=None))
self.addParameter(QgsProcessingParameterFeatureSink('joint', 'jointure', optional=True, type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))
self.addParameter(QgsProcessingParameterFeatureSink('output', 'final output', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, supportsAppend=True, defaultValue=None))
self.addParameter(QgsProcessingParameterFolderDestination('save', 'Save to folder :', createByDefault=True, defaultValue=None))
def processAlgorithm(self, parameters, context, model_feedback):
feedback = QgsProcessingMultiStepFeedback(15, model_feedback)
results = {}
outputs = {}
# lot of algorithms process
# example of one of my ouputs/results
outputs['RefactorSite'] = processing.run('native:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
results['final output'] = outputs['RefactorSite']['OUTPUT']
# pass results to post processing
self.dest_id['One_of_my_processing_outputs'] = QgsProcessingUtils.mapLayerFromString(results['One_of_my_processing_outputs'], context)
return results
Then I want to pass processed layers to post process to zip all of them to the specified folder
def postProcessAlgorithm(self, context, feedback):
filenames = QgsProcessingUtils.mapLayerFromString(self.dest_id, context)
with zipfile.ZipFile("multiple_files.zip", mode="w") as archive:
for filename in filenames:
archive.write(filename)
return {}
My code does not work and throws this error:
"TypeError: QgsProcessingUtils.mapLayerFromString(): argument 1 has unexpected type 'QgsVectorLayer' " or "unexpected type 'dict' "
Here is the documentation for QgsProcessingUtils.mapLayerFromString()
.
What is wrong with my code?
os.remove