You may continue using the memory layer by loading it as an object. Before doing this, you need to know how the output from the algorithm is called, so typing these lines in the Python Console:
import processing
processing.alghelp('qgis:fieldcalculator')
you will see that the output's name is OUTPUT_LAYER
:
ALGORITHM: Field calculator
INPUT_LAYER <ParameterVector>
FIELD_NAME <ParameterString>
FIELD_TYPE <ParameterSelection>
FIELD_LENGTH <ParameterNumber>
FIELD_PRECISION <ParameterNumber>
NEW_FIELD <ParameterBoolean>
FORMULA <ParameterString>
OUTPUT_LAYER <OutputVector>
FIELD_TYPE(Field type)
0 - Float
1 - Integer
2 - String
3 - Date
This means that you will be able to use it if you add a new variable and call it in this way:
# change 'my_output' name as you want
my_output = processing.getObject(outputs_QGISFIELDCALCULATOR_4['OUTPUT_LAYER'])
By now, you are ready to do something with it.
EDIT
From a more general point of view, I would use this code for accomplish both the tasks described in the question:
# see the using of 'runalg' instead of 'runandload' and the using of 'None'
outputs_QGISFIELDCALCULATOR_4=processing.runalg('qgis:fieldcalculator', outputs_QGISFIELDCALCULATOR_3['OUTPUT_LAYER'],'newnew',2,50.0,0.0,True,'left(\"TOP_KOIN\", strpos(\"TOP_KOIN\" ,\' \')-1)',None)
# the following for loading the previous output in the Layers Panel with a custom name
load_it = QgsVectorLayer(outputs_QGISFIELDCALCULATOR_4['OUTPUT_LAYER'], 'type here the name you want', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(load_it)
# change 'my_output' name as you want
my_output = processing.getObject(outputs_QGISFIELDCALCULATOR_4['OUTPUT_LAYER'])
# by now, 'my_output' will be the object to use for calling the layer returned by 'qgis:fieldcalculator' for further operations.
You can change it in def initAlgorithm()
. Just enter the name you wish in the specific parameter within self.tr()
:
self.addParameter(
QgsProcessingParameterFeatureSink(
self.OUTPUT, self.tr('Enter your desired Name here')))
To make the name dynamic, you need to follow this answer like this:
def processAlgorithm(self, parameters, context, feedback):
# your script
# ....
# make sure source_layer is a layer, like: source_layer = self.parameterAsLayer(parameters, self.INPUT, context)
global renamer
newname = '{}_to_DMS'.format(source_layer.name())
renamer = Renamer(newname)
context.layerToLoadOnCompletionDetails(dest_id).setPostProcessor(renamer)
return {self.OUTPUT: dest_id}
class Renamer (QgsProcessingLayerPostProcessorInterface):
def __init__(self, layer_name):
self.name = layer_name
super().__init__()
def postProcessLayer(self, layer, context, feedback):
layer.setName(self.name)
Here is the complete example from QGIS template, with this part added:
# -*- 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 qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing, QgsProcessingLayerPostProcessorInterface,
QgsFeatureSink,
QgsProcessingException,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink)
from qgis 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.
INPUT = 'INPUT'
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.
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
)
source_layer = self.parameterAsLayer(parameters, self.INPUT, context)
# If source was not found, throw an exception to indicate that the algorithm
# encountered a fatal error. The exception text can be any string, but in this
# case we use the pre-built invalidSourceError method to return a standard
# helper text for when a source cannot be evaluated
if source is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
(sink, dest_id) = self.parameterAsSink(
parameters,
self.OUTPUT,
context,
source.fields(),
source.wkbType(),
source.sourceCrs()
)
#
# Send some information to the user
feedback.pushInfo('CRS is {}'.format(source.sourceCrs().authid()))
# If sink was not created, throw an exception to indicate that the algorithm
# encountered a fatal error. The exception text can be any string, but in this
# case we use the pre-built invalidSinkError method to return a standard
# helper text for when a sink cannot be evaluated
if sink is None:
raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
# 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))
# To run another Processing algorithm as part of this algorithm, you can use
# processing.run(...). Make sure you pass the current context and feedback
# to processing.run to ensure that all temporary layer outputs are available
# to the executed algorithm, and that the executed algorithm can send feedback
# reports to the user (and correctly handle cancellation and progress reports!)
if False:
buffered_layer = processing.run("native:buffer", {
'INPUT': dest_id,
'DISTANCE': 1.5,
'SEGMENTS': 5,
'END_CAP_STYLE': 0,
'JOIN_STYLE': 0,
'MITER_LIMIT': 2,
'DISSOLVE': False,
'OUTPUT': 'memory:'
}, context=context, feedback=feedback)['OUTPUT']
# 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.
global renamer
newname = '{}_to_DMS'.format(source_layer.name())
renamer = Renamer(newname)
context.layerToLoadOnCompletionDetails(dest_id).setPostProcessor(renamer)
return {self.OUTPUT: dest_id}
class Renamer (QgsProcessingLayerPostProcessorInterface):
def __init__(self, layer_name):
self.name = layer_name
super().__init__()
def postProcessLayer(self, layer, context, feedback):
layer.setName(self.name)
Best Answer
Processing offers two approaches:
You can change the behavior in the Processing options: