2

I make points everyday and make it into a polygon and merge it to the previous polygon I have already made

enter image description here

The format of the points are in yyyy-mm-dd_Points and the polygon format is yyyymmdd_progress which is stored in my folder.

My code primarily generates polygon (variable polygon) by buffer (but I'm also open to suggestions better way to generate polygon from points), then I will manually paste the directory to the variable lay1, then it will get merged.

How can I get the directory of the layer I want to merge with the polygon I just created?

So this is my code:

  from qgis import processing
from datetime import datetime, timedelta


path_file = f'C:/Users/CMCA/Downloads'

date = datetime.strftime(datetime.now() - timedelta(2), "%Y%m%d") 
lay1 = path_file +'/'+f'{date}'+'_progress'+'.gpkg'

#lay1 = 'C:/Users/CMCA/OneDrive - Boskalis/Documents/20230323_PVDprogress.gpkg'
inlayDir = iface.activeLayer()



print("Start Polygon Process...")
print("Generating polygon")
polygon = processing.runAndLoadResults("native:buffer", 
               {'INPUT':inlayDir,
               'DISTANCE':1.5,
               'SEGMENTS':2,
               'END_CAP_STYLE':0,
               'JOIN_STYLE':0,
               'MITER_LIMIT':2,
               'DISSOLVE':True,
               'OUTPUT':'TEMPORARY_OUTPUT'})
               
               
polygon = polygon['OUTPUT']
columns_to_delete_indx = polygon.attributeList()
polygon.startEditing()
polygon.dataProvider().deleteAttributes(columns_to_delete_indx)
polygon.commitChanges()

print("merging...")
merge = processing.runAndLoadResults("native:mergevectorlayers",{'LAYERS':[lay1,polygon],
                                         'CRS':QgsCoordinateReferenceSystem('USER:100000'),
                                         'OUTPUT':'TEMPORARY_OUTPUT'})

Error:

  Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 31, in <module>
AttributeError: 'str' object has no attribute 'attributeList'

This is the whole code I've done so far but I am having trouble with the errors :

    from qgis import processing
    from datetime import datetime, timedelta
    
    
    path_file = f'C:/Users/CMCA/Downloads'
    
    date = datetime.strftime(datetime.now() - timedelta(2), "%Y%m%d") # or "%Y%m%d_%H%M%S"
    lay1 = path_file +'/'+f'{date}'+'_progress'+'.gpkg'
    
    #lay1 = 'C:/Users/CMCA/OneDrive - Boskalis/Documents/20230327_PVDprogress.gpkg'
    inlayDir = iface.activeLayer()
    P3_boundary = 'D:/QGIS/General/PhaseRev3_BoundariesOutside_v2.gpkg'
    
    clustering = processing.runAndLoadResults("native:dbscanclustering",
                                              {'INPUT':inlayDir,
                                              'MIN_SIZE':5,
                                              'EPS':2,
                                              'DBSCAN*':False,
                                              'FIELD_NAME':'CLUSTER_ID',
                                              'SIZE_FIELD_NAME':'CLUSTER_SIZE',
                                              'OUTPUT':'TEMPORARY_OUTPUT'})
                                              
    concave_Hull = processing.runAndLoadResults("qgis:concavehull",
                                                {'INPUT':clustering['OUTPUT'],
                                                'ALPHA':0.01,
                                                'HOLES':True,
                                                'NO_MULTIGEOMETRY':True,
                                                'OUTPUT':'TEMPORARY_OUTPUT'})
    print("Generating polygon")
    
    buffer = processing.run("native:buffer",
                  {'INPUT':concave_Hull['OUTPUT'],
                   'DISTANCE':1,
                   'SEGMENTS':5,
                   'END_CAP_STYLE':2,
                   'JOIN_STYLE':0,
                   'MITER_LIMIT':2,
                   'DISSOLVE':True,
                   'OUTPUT':'TEMPORARY_OUTPUT'})
                   
                   
    polygon = buffer['OUTPUT']
    columns_to_delete_indx = polygon.attributeList()
    polygon.startEditing()
    polygon.dataProvider().deleteAttributes(columns_to_delete_indx)
    polygon.commitChanges()
    polygon = iface.activeLayer()
    
    print("merging...")
    
    merge = processing.runAndLoadResults("native:mergevectorlayers",{'LAYERS':[lay1,polygon],
                                             'CRS':QgsCoordinateReferenceSystem('USER:100000'),
                                             'OUTPUT':'TEMPORARY_OUTPUT'})



Error:
Generating polygon
merging...
Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 53, in <module>
  File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python/plugins\processing\tools\general.py", line 151, in runAndLoadResults
    return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback,
  File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python/plugins\processing\core\Processing.py", line 181, in runAlgorithm
    raise QgsProcessingException(msg)
_core.QgsProcessingException: Unable to execute algorithm
Incorrect parameter value for LAYERS
8
  • 1
    I'm not clear from the current version of your question what your process is, or what specifically you are asking for help with. Can you clarify? Mar 26, 2023 at 7:23
  • i edited my statement above , I hope this is clear
    – charliey
    Mar 26, 2023 at 13:43
  • 1
    The error you get is because dir is a reserved keyword in Python. Hence the built-in function or method part of the error. Having said that, you can't have defined your dir variable because if you had, it would have overwritten the built-in function.
    – Matt
    Mar 26, 2023 at 13:55
  • 2
    Does the error correspond to the new code? According to the code in your question you are no longer trying to add a built-in function or method and a string. Please include all relevant code, otherwise it is difficult to help you. You also miss the f from the beginning of your f string (the string with the curly braces {}).
    – Matt
    Mar 26, 2023 at 15:15
  • 2
    This thread is becoming very muddled with the error reported being changed, reframing of the question, and now two different scripts at once. There are already 2 valid answers to the problem previously stated. I would recommend rolling back your edits and opening a new question for your new problem.
    – Matt
    Mar 29, 2023 at 8:55

2 Answers 2

6

In the last version of your question, use processing.run instead of processing.runAndLoadResults. Because runAndLoadResults methods returns {'OUTPUT': 'buffer_0ae....'}. So polygon['OUTPUT'] gives you a string. That's why you're getting the error.

Instead, use processing.run. It returns {'OUTPUT': <qgis._core.QgsVectorLayer object at 0x00...>}. In this case, polygon["OUTPUT"] gives you the layer reference in memory and you don't get that error.

Please review this answer for more detailed information.

In a nutshell, use this:

polygon = processing.run("native:buffer", ... 
polygon = polygon['OUTPUT']

If you need to add the buffer layer to the project, use also:

QgsProject.instance().addMapLayer(polygon)
4

Calling 'OUTPUT' on the result of processing.runAndLoadResults returns a Map Layer ID (a string), not a QgsMapLayer.

Add this to get a reference to the layer:

polygon = polygon['OUTPUT']

# add this line
polygon = QgsProject.instance().mapLayer(polygon)

# should now work
columns_to_delete_indx = polygon.attributeList()
2
  • I have added the whole script i made so far here, if you could please check what is wrong ?
    – charliey
    Mar 29, 2023 at 5:29
  • I got another Error: Traceback (most recent call last): File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 45, in <module> TypeError: QgsProject.mapLayer(): argument 1 has unexpected type 'QgsVectorLayer'
    – charliey
    Mar 29, 2023 at 9:09

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