I am trying to run an elementary piece of Python code, that simply loads a dem file as a raster accessing the QGIS Python API.

On the embedded console (within the QGIS application GUI), it runs fine and the raster loads. However, it does not load work when I run it outside of the embedded console, from a standard windows prompt AFTER setting up QGIS_PREFIX_HOME and PYTHONPATH using a batch file.

The code I am running is as follows:

import os

from PyQt4.QtCore import QFileInfo, QSettings
from qgis.core import *

# load providers

# Load an input dem
rasterFile = "E:\\data\\43j11\\43J11.dt2"
fileInfo = QFileInfo(rasterFile)    
baseName = fileInfo.baseName()
print "Loading raster layer:" + fileName

if fileInfo.exists():
    print "Raster file specified exists."
    print "File does not exist"

errorStr = "Unknown"
if QgsRasterLayer.isValidRasterFileName(rasterFile, errorStr):
    print "File is a valid raster"
    rlayer = QgsRasterLayer(rasterFile, baseName)
    if not rlayer.isValid():
        print "Layer failed to load!"
        print "Successfully loaded dem: " + fileName    
    print "File is not a valid raster. Error: " + errorStr  


Within the embedded console, the output I get is:

Loading raster layer:43J11.dt2
Raster file specified exists.
File is a valid raster
Successfully loaded dem: 43J11.dt2

Outside the embedded console, the output I get is:

Loading raster layer:43J11.dt2
Raster file specified exists.
File is not a valid raster. Error: Unknown

I suspect this is a path/initialization problem, so I am also including the .bat file I am using here:

set QGIS_PREFIX_PATH=C:\Program Files\QGIS Wien

I need it to work outside of the embedded console since I need to package QGis as part of my application. My eventual plan is to include a .bat file where I will set the QGIS_PREFIX_HOME from my application's installer.

  • 1
    @gcarrillo That did the trick. Can you please convert your comment to an answer so that I can accept it as one? – balajeerc Apr 1 '15 at 5:02

I think you need to include this line:

QgsApplication.setPrefixPath("C:\\Program Files\\QGIS Wien\\apps\\qgis", True) 

right before this one:

| improve this answer | |

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.