3

I have a PyQGIS script that I exported from a QGIS process model. I have set output layer names that make sense in the model but when I export and run the model in PyQGIS it outputs the temporary names eg: "Centroid", "Refactor" etc. rather than the layer names I set in original model.

How can I get the PyQGIS to export to a QGIS canvas layer that I stipulate?

QgsProcessing.TEMPORARY_OUTPUT

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
import processing


class BcPolygonReport(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterVectorLayer('countyregion', 'County / Region (county_region_bc)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='County / Region (county_region_bc)'))
        self.addParameter(QgsProcessingParameterVectorLayer('crownlandleasesandpermitstacrtsvwpolygon', 'Crown Land Leases and Permits (ta_crt_svw_polygon)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Crown Land Leases and Permits (ta_crt_svw_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('crownlandrightsofway', 'Crown Land Rights-of-Way', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Crown Land Rights-of-Way (ta_crw_svw_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('forestcoverreserve', 'Results Forest Cover Reserve', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Results Forest Cover Reserve (rslt_fcres_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('forestharvestauthorizationsftnhasvwpolygon', 'Forest Harvest Authorizations (ftn_ha_svw_polygon)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Forest Harvest Authorizations (ftn_ha_svw_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('foresttenurecutblocksftncbplpolygon', 'Forest Tenure Cut Blocks (ftn_c_b_pl_polygon)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Forest Tenure Cut Blocks (ftn_c_b_pl_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('foresttenureroadsegment', 'Forest Tenure Access', types=[QgsProcessing.TypeVectorLine], defaultValue='Forest Tenure Access (ften_rs_ln_line)'))
        self.addParameter(QgsProcessingParameterVectorLayer('foresttenurespecialaccessroad', 'Forest Tenure Special Access Road', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Forest Tenure Special Access Road (ftn_s_ac_r_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('foresttenuretimberlicense', 'Forest Tenure Timber License', types=[QgsProcessing.TypeVectorPolygon], defaultValue='Forest Tenure Timber License (ften_tl_py_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('guideoutfitterboundary', 'Guide_Outfitter (waagoa_svw_polygon)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Guide_Outfitter (waagoa_svw_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('mineralandcoaltitles', 'Mineral and Coal Titles', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Mineral and Coal Titles (mta_acq_te_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('pmbc', 'PMBC', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='pmbc_unique_merged'))
        self.addParameter(QgsProcessingParameterVectorLayer('rangetenure', 'Range Tenure (ftn_rng_py_polygon)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Range Tenure (ftn_rng_py_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('resultsopeningsrsltopngspolygon', 'Results Openings (rslt_opngs_polygon)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Results Openings (rslt_opngs_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('tantalussurveyedparcels', 'Tantalus Surveyed Parcels', types=[QgsProcessing.TypeVectorPolygon], defaultValue='Tantalis Surveyed Parcels (ta_sp_svw_polygon_)'))
        self.addParameter(QgsProcessingParameterVectorLayer('tantalussurveyedrightofway', 'Tantalus Surveyed Right-of-Way', types=[QgsProcessing.TypeVectorPolygon], defaultValue='Tantalus Surveyed Right-of-Way (ta_srp_svw_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('trapperboundary', 'Trappers (waatrp_ars_polygon)', optional=True, types=[QgsProcessing.TypeVectorPolygon], defaultValue='Trappers (waatrp_ars_polygon)'))
        self.addParameter(QgsProcessingParameterVectorLayer('wellcentre', 'Polygon Set', types=[QgsProcessing.TypeVectorPolygon], defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Reportpmbc', 'Report-PMBC', type=QgsProcessing.TypeVectorPoint, createByDefault=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('ReportrangesAndAreas', 'Report-Ranges and Areas', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('ReportmergedForestryTenures', 'Report-Merged Forestry Tenures', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('ReportrightsofwayAndLeases', 'Report-Rights-of-Way and Leases', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('ReportresultsForestTenureRoadSegments', 'Report-Results Forest Tenure Road Segments', 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(50, model_feedback)
        results = {}
        outputs = {}

        # Extract Forest Tenure Access
        alg_params = {
            'INPUT': parameters['foresttenureroadsegment'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractForestTenureAccess'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Mineral and Coal Titles
        alg_params = {
            'INPUT': parameters['mineralandcoaltitles'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractMineralAndCoalTitles'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Trapper
        alg_params = {
            'INPUT': parameters['trapperboundary'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractTrapper'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Tantalus Surveyed Parcels
        alg_params = {
            'INPUT': parameters['tantalussurveyedparcels'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': [0],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractTantalusSurveyedParcels'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract PMBC
        alg_params = {
            'INPUT': parameters['pmbc'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractPmbc'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Harvest Auth
        alg_params = {
            'INPUT': parameters['forestharvestauthorizationsftnhasvwpolygon'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractHarvestAuth'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Forest Tenure Special Access Road
        alg_params = {
            'INPUT': parameters['foresttenurespecialaccessroad'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractForestTenureSpecialAccessRoad'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Refactor Trapper
        alg_params = {
            'FIELDS_MAPPING': [{'expression': '', 'length': 4, 'name': 'Map Number', 'precision': 0, 'type': 2}, {'expression': "'Trapper ID.'", 'length': 56, 'name': 'Source', 'precision': 0, 'type': 10}, {'expression': 'case\r\nwhen "trpln_iden" is null\r\nthen \'None\'\r\nwhen "trpln_iden" = \'\'\r\nthen \'None\'\r\nElse "trpln_iden"\r\nend', 'length': 24, 'name': 'Gov. ID No.', 'precision': 0, 'type': 10}, {'expression': "'B.C. Trapper Assoc.'", 'length': 255, 'name': 'Description', 'precision': 0, 'type': 10}, {'expression': '', 'length': 56, 'name': 'Owner / Holder', 'precision': 0, 'type': 10}],
            'INPUT': outputs['ExtractTrapper']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['RefactorTrapper'] = processing.run('qgis:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Crown Land Rights-of-Way
        alg_params = {
            'INPUT': parameters['crownlandrightsofway'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': [0],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractCrownLandRightsofway'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Crown Land Leases and Permits
        alg_params = {
            'INPUT': parameters['crownlandleasesandpermitstacrtsvwpolygon'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': [0],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractCrownLandLeasesAndPermits'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Range / Tenure
        alg_params = {
            'INPUT': parameters['rangetenure'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractRangeTenure'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Crown Land Leases and Permits
        alg_params = {
            'EXPRESSION': '\"ten_type\" = \'INVENTORY\'\r\nor\r\n\"ten_type\" = \'LEASE\'\r\nor\r\n\"ten_type\" = \'PERMIT\'\r\nor\r\n\"ten_type\" = \'RIGHT-OF-WAY\'\r\nor\r\n\"ten_type\"=\'RESERVE/NOTATION\'\r\nor\r\n\"ten_type\"=\'LICENCE\'\r\n',
            'INPUT': outputs['ExtractCrownLandLeasesAndPermits']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractCrownLandLeasesAndPermits'] = processing.run('native:extractbyexpression', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Refactor Mineral and Coal Titles
        alg_params = {
            'FIELDS_MAPPING': [{'expression': '', 'length': 4, 'name': 'Map Number', 'precision': 0, 'type': 2}, {'expression': "'Mineral Coal Titles'", 'length': 56, 'name': 'Source', 'precision': 0, 'type': 10}, {'expression': '"tnrnmbrd"', 'length': 24, 'name': 'Gov. ID No.', 'precision': 0, 'type': 10}, {'expression': '"tnrtpdscrp"', 'length': 255, 'name': 'Description', 'precision': 0, 'type': 10}, {'expression': '"owner_name"', 'length': 56, 'name': 'Owner / Holder', 'precision': 0, 'type': 10}],
            'INPUT': outputs['ExtractMineralAndCoalTitles']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['RefactorMineralAndCoalTitles'] = processing.run('qgis:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Results Openings
        alg_params = {
            'INPUT': parameters['resultsopeningsrsltopngspolygon'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractResultsOpenings'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Forest Tenure Timber License
        alg_params = {
            'INPUT': parameters['foresttenuretimberlicense'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractForestTenureTimberLicense'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract County / Region
        alg_params = {
            'INPUT': parameters['countyregion'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractCountyRegion'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Guide / Outfitter
        alg_params = {
            'INPUT': parameters['guideoutfitterboundary'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractGuideOutfitter'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Results Forest Cover Reserve
        alg_params = {
            'INPUT': parameters['forestcoverreserve'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractResultsForestCoverReserve'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Tantalus Parcel Subdivisions
        alg_params = {
            'FIELD': 'prcltp',
            'INPUT': outputs['ExtractTantalusSurveyedParcels']['OUTPUT'],
            'OPERATOR': 0,
            'VALUE': 'Subdivision',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractTantalusParcelSubdivisions'] = processing.run('native:extractbyattribute', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract Forest Tenure
        alg_params = {
            'INPUT': parameters['foresttenurecutblocksftncbplpolygon'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': 0,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractForestTenure'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Extract by Tantalus Surveyed Right-of-Way
        alg_params = {
            'INPUT': parameters['tantalussurveyedrightofway'],
            'INTERSECT': parameters['wellcentre'],
            'PREDICATE': [0],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExtractByTantalusSurveyedRightofway'] = processing.run('native:extractbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Refactor Tantalus Surveyed Parcels
        alg_params = {
            'FIELDS_MAPPING': [{'expression': '"prcllgldsc"', 'length': 255, 'name': 'prcllgldsc', 'precision': 0, 'type': 10}],
            'INPUT': outputs['ExtractTantalusParcelSubdivisions']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['RefactorTantalusSurveyedParcels'] = processing.run('qgis:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

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

        # Refactor Forest Road Segment
        alg_params = {
            'FIELDS_MAPPING': [{'expression': '', 'length': 4, 'name': 'Map Number', 'precision': 0, 'type': 2}, {'expression': "'Forest Tenure Road Segment'", 'length': 56, 'name': 'Source', 'precision': 0, 'type': 10}, {'expression': '"ffid"', 'length': 24, 'name': 'Gov. ID No.', 'precision': 0, 'type': 10}, {'expression': ' "life_st_cd"', 'length': 255, 'name': 'Description', 'precision': 0, 'type': 10}, {'expression': '"rd_sect_nm"', 'length': 56, 'name': 'Owner / Holder', 'precision': 0, 'type': 10}],
            'INPUT': outputs['ExtractForestTenureAccess']['OUTPUT'],
            'OUTPUT': parameters['ReportresultsForestTenureRoadSegments']
        }
        outputs['RefactorForestRoadSegment'] = processing.run('qgis:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['ReportresultsForestTenureRoadSegments'] = outputs['RefactorForestRoadSegment']['OUTPUT']

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

1 Answer 1

3

Not to struggle with all those classes, language dependencies and changes to the api, I use following since QGIS 2.x (console):

class myProcessing(QObject):
    def __init__(self, cmd, parameters):
        super(myProcessing, self).__init__()
        try:
            self.layer=None
            self.prj=QgsProject.instance()
            self.prj.layerWasAdded.connect(self.layer_added)
            processing.runAndLoadResults(cmd,parameters)
            self.prj.layerWasAdded.disconnect(self.layer_added)
        except Exceptions as e:
            print(e)
            self.prj.layerWasAdded.disconnect(self.layer_added)

    def layer_added(self,layer):
        self.layer=layer

input_layer = QgsProject.instance().mapLayersByName('lines')[0]  
cmd="grass7:v.parallel"
parameters ={'distance':20,'side':1,'output':'TEMPORARY_OUTPUT'}
parameters['input']=QgsProcessingFeatureSourceDefinition(input_layer.name(), True)
proc=myProcessing(cmd,parameters)
out_layer=proc.layer
print(out_layer.name())

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.