[GIS] Using processing.runalg in python script

pyqgisqgisqgis-processing

I'm trying to run the following python script:

from qgis.core import *
import sys
import os
import qgis.utils
from qgis.analysis import *

app = QgsApplication([],True,"")

# supply path to where is your qgis installed
QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True)

# load providers
QgsApplication.initQgis()

sys.path.append("/Applications/QGIS.app/Contents/Resources/python/plugins")
import processing

layer3 = QgsVectorLayer("../output/precinctsZipcodes.shp", "intersect", "ogr")
if layer3.isValid():
    print "Loaded layer 3"
else:
    print "Layer 3 failed to load!"

processing.runalg("qgis:exportaddgeometrycolumns", layer3, 0, "../output/precinctsZipcodesArea.shp")

QgsApplication.exitQgis()

However, the line processing.runalg("qgis:exportaddgeometrycolumns", layer3, 0, "../output/precinctsZipcodesArea.shp") isn't saving any output. The strange thing is that this syntax works when I run it directly in the python console. Does anybody know what might be happening?

Best Answer

Not sure of what could be happening there, but the next code snippet has worked for me on my GNU/Linux machine:

# Prepare the environment
import sys
from qgis.core import *
from PyQt4.QtGui import *
app = QApplication([])
QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()

# Prepare processing framework 
sys.path.append('/home/germap/.qgis2/python/plugins')
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *

# Run the algorithm
layerInput = QgsVectorLayer('world_adm0.shp', 'test', 'ogr')
general.runalg("qgis:exportaddgeometrycolumns", layerInput, 0, "tmp.shp")

# Exit applications
QgsApplication.exitQgis()
QApplication.exit()

I successfully got the tmp.shp file saved in the folder from which I run the script. Could you give it a try? Just adjust QGIS prefix and other paths to reflect your system configuration.