Issue when running refactorfields from the python console

pyqgisqgis-processing

I've an issue when trying to run the processing tool refactor fields from the python console. I'm trying to write a script that acts as a macro and refactors layers with well known fields into another layer, as well with well known fields properties.

After importing the processing library and defining the input and output path, that's what i wrote:

 ----------
 processing.run("'native:refactorfields'", input, [{'name':"NEWID", 'type':0, 'length':3,
'precision':2, 'expression':"id"}], output)
 ----------

That's only a first try, I wanted to see if the algorithm works before to write the new properties for all fields. That's the error warning I get:

----------
Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS3~1.16\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "C:/PROGRA~1/QGIS3~1.16/apps/qgis-ltr/./python/plugins\processing\tools\general.py", line 108, in run
    return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context)
  File "C:/PROGRA~1/QGIS3~1.16/apps/qgis-ltr/./python/plugins\processing\core\Processing.py", line 159, in runAlgorithm
    context = dataobjects.createContext(feedback)
  File "C:/PROGRA~1/QGIS3~1.16/apps/qgis-ltr/./python/plugins\processing\tools\dataobjects.py", line 67, in createContext
    context.setFeedback(feedback)
TypeError: QgsProcessingContext.setFeedback(): argument 1 has unexpected type 'str'
----------

i'm using QGIS 3.16.6 Hannover with GRASS.

Best Answer

The parameters of a processing algorithm must be a dictionary, for example:

processing.run("native:refactorfields", {'INPUT': input, 'FIELDS_MAPPING': [{'name':"NEWID", 'type':0, 'length':3, 'precision':2, 'expression':"id"}], 'OUTPUT': output})

In your code, the first parameter must be this dictionary which contains every parameters to use the algorithm. Your input path, a string is passed as this dictionary creating a type error. You also had double quote and single quote around your algorithm name. I recommend you to use the processing history to help you write your script.

Related Question