AttributeError: 'QgsProject' object has no attribute 'addMapLayer'

0

I am running the following script on Ubuntu terminal to create a polygon from points in a csv file.

#!/usr/bin/python

from qgis.core import *
     
QgsApplication.setPrefixPath('/usr', True)

qgs = QgsApplication([], False)

qgs.initQgis()

# Put your pyqgis code here:
uri = "file:////home/aka000/site4/PyQGIS/Tailings_Pond_1A.csv?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s" % ("UTF-8",",", "Lat", "Long","epsg:4326")

#Make a vector layer
eq_layer=QgsVectorLayer(uri,"eq-data","delimitedtext")

#Check if layer is valid
if not eq_layer.isValid():
    print ("Layer not loaded")

#Add CSV data    
QgsProject.instance().addMapLayer(eq_layer)

points = [QgsPointXY(f['long'], f['lat']) for f in iface.activeLayer().getFeatures()]
poly = QgsGeometry.fromPolygonXY([points]) #Create a polygon geometry

#Create a empty memory layer
vl = QgsVectorLayer("Polygon?crs=EPSG:4326&index=yes", "myLayer", "memory")
provider = vl.dataProvider()

newfeature = QgsFeature()
newfeature.setGeometry(poly)
provider.addFeature(newfeature)
QgsProject.instance().addMapLayer(vl)

# Finally, exitQgis() is called to remove the
# provider and layer registries from memory
qgs.exitQgis()

Here is the error I get:

File "./test.py", line 23, in <module>
QgsProject.instance().addMapLayer(eq_layer)
AttributeError: 'QgsProject' object has no attribute 'addMapLayer'

I wrote the same script in python console in windows and it worked well, but I need to run it on Linux:

ri = "file:///C:/Users/katala/Desktop/PyQGIS/Tailings Pond 1A.csv?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s" % ("UTF-8",",", "Lat", "Long","epsg:4326")

#Make a vector layer
eq_layer=QgsVectorLayer(uri,"eq-data","delimitedtext")

#Check if layer is valid
if not eq_layer.isValid():
    print ("Layer not loaded")

#Add CSV data    
QgsProject.instance().addMapLayer(eq_layer)

points = [QgsPointXY(f['long'], f['lat']) for f in iface.activeLayer().getFeatures()]
poly = QgsGeometry.fromPolygonXY([points]) #Create a polygon geometry

#Create a empty memory layer
vl = QgsVectorLayer("Polygon?crs=EPSG:4326&index=yes", "myLayer", "memory")
provider = vl.dataProvider()

newfeature = QgsFeature()
newfeature.setGeometry(poly)
provider.addFeature(newfeature)
QgsProject.instance().addMapLayer(vl)

Hi alikatal,
this is the wrong forum for you question. This Forum is for SNAP and related software.
For QGIS you can use one of the support channels stated on their webpage
Get Involved / Development (qgis.org) or raise directly an issue in the issues tracker Issues · qgis/pyqgis (github.com).

1 Like