4

I have a vector layer which I need to load and edit (add several attribute columns). I am doing this without opening QGIS, so within a Python script. I have the following piece of code for the layer loading:

from osgeo import gdal
from osgeo import ogr

from gdalconst import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *


layer = QgsVectorLayer("/home/usr/Desktop/EligibleAreas_polygons.shp", "EligibleAreas_polygons", "ogr")
if not layer.isValid():
    print "Eligible areas layer failed to load!"

When I execute the Python script I get the message that the shapefile could not be loaded. When I try executing the same script from the Python console in QGIS, I get no warning. What could be the problem?

When I execute the next step (creating an attribute column "Land_Area" of doubles) within the Python console:

# add new fields
layer.addAttribute(QgsField("LandArea", QVariant.Double))

I get False. Can someone give me a suggestion on how to solve this?

6

From the documentation Using PyQGIS in custom application, you need to add the paths to where QGIS is installed and load its providers before you can use its features and tools:

from qgis.core import *

# supply path to where is your qgis installed
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)

# load providers
QgsApplication.initQgis()

And end your script with the following to do a clean up:

QgsApplication.exitQgis()

Edit:

Few things to note:

  • You may need to add the qgis application class reference object app = QApplication([], True)

  • To add attributes to the shapefile, you need to use addAttributes() and not addAttribute (not plural). This can only be done by first accessing the layer's dataProvider().

The following script works for me (note that you will need to change your paths as I use Windows):

from osgeo import gdal
from osgeo import ogr

from gdalconst import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *

QgsApplication( [], False, home + "/AppData/Local/Temp" )
QgsApplication.setPrefixPath("C://OSGeo4W64//apps//qgis", True)
app = QApplication([], True)
QgsApplication.initQgis()

layer = QgsVectorLayer("/home/usr/Desktop/EligibleAreas_polygons.shp", "EligibleAreas_polygons", "ogr")
if not layer.isValid():
    print "Eligible areas layer failed to load!"

layer.dataProvider().addAttributes( [ QgsField("LandArea",QVariant.Double) ] )

QgsApplication.exitQgis()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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