I have the following code which I have no problem executing within QGIS (2.8.6) via the python console. What the script does is it adds the two raster layers in my directory via the Raster Calculator:

from osgeo import gdal
from osgeo import ogr

from gdalconst import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.analysis import * 
from qgis.gui import *
import sys
import glob
import re 
import os, fnmatch
import numpy as np
import numpy.ma as ma
import math 
import subprocess 

qgisprefix = '/usr'

# configure paths for QGIS 
os.environ['PATH'] = qgisprefix+'/bin'
os.environ['LD_LIBRARY_PATH'] = qgisprefix+'/lib'
sys.path.insert(0, qgisprefix+'/share/qgis/python')
sys.path.insert(1, qgisprefix+'/share/qgis/python/plugins')

# disable QGIS debug messages
os.environ['QGIS_DEBUG'] = '-1'

# configure QGIS paths
QgsApplication.setPrefixPath(qgisprefix, True)

# initalise QGIS (load providers)

#Load all the rasters  
outputFolder = "/home/usr/Desktop/Output/"
extent = QgsRectangle(264885.85754, 5073773.01243, 614325.85754, 5295173.01243)
numCols = 11648
numRows = 7380

entries = []

for fname in glob.glob("*.tif"):
    fileInfo = QFileInfo(fname) 
    baseName = fileInfo.baseName() 
    rasterLayer = QgsRasterLayer(fname, baseName)
    mc = iface.mapCanvas()
    Layers = mc.layers()
    for each_layer in Layers:
        layerR = QgsRasterCalculatorEntry()
        layerR.ref = each_layer.name() + '@1'
        layerR.raster = each_layer 
        layerR.bandNumber = 1

expression = '('+entries[1].ref+'+'+entries[0].ref+')' #re-write that to include all rasters 
calc = QgsRasterCalculator(expression, "/home/usr/Desktop/Output/final.tif",'GTiff',extent,numCols,numRows,entries)

When I try to execute the same code outside QGIS in a standalone script, I get no errors but there is nothing in my Output folder. What should I adapt in order to be able to run the script outside of QGIS?

  • 2
    Have a look at this answer from @underdark: gis.stackexchange.com/questions/30063/… Feb 25, 2016 at 17:30
  • I'm sorry, I did not include this part of my code, but it is in the python script just as indicated in the link you attached. Unfortunately, there is no output
    – ELD
    Feb 25, 2016 at 17:47

1 Answer 1


Try adding

app = QgsApplication([],False, None) before QgsApplication.initQgis() in your script:

# configure QGIS paths
QgsApplication.setPrefixPath(qgisprefix, True)

# initalise QGIS (load providers)
app = QgsApplication([],False, None)

and end the script with:


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