2

I'm working on a project using the QGIS Python API. I seem to be having some issues with opening a vector layer from a shapefile in my standalone application. This is the Python script I'm using to test opening the layer:

#   Import statements
from qgis.core import *
import os

#   Instantiate the QGIS Application
GUIEnabled = True
app = QgsApplication([], GUIEnabled)
#   Update prefix path
app.setPrefixPath("C:\OSGeo4W64\apps\qgis", True)
app.initQgis()

#   File to be read by the application
vector_source = "absolute_path_to_file"

#   Read layer from file
layer = QgsVectorLayer(vector_source, "Vector_Layer", "ogr")

#   DEBUG: Test if the file path points to a valid file
print "File Path points to a file: ", os.path.isfile(vector_source)

#   DEBUG: Test if the layer initialized correctly
print "Output of layer.isValid(): ", layer.isValid()

layer.isValid() returns false when I run the script. I checked to make sure the file was valid by opening it in the QGIS GUI, which worked. I also checked out the answer to Creating QGIS layers in python console vs stand-alone application, but the answer there is specific to Mac users, and I am running on Windows 8.

2

You need to escape your backslashes when you defined your paths for the QGIS application (I tend to use forward slashes).

So you should replace:

app.setPrefixPath("C:\OSGeo4W64\apps\qgis", True)

with:

app.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)

or:

app.setPrefixPath(r"C:\OSGeo4W64\apps\qgis", True)

Example

  • 1
    Thank you. This resolved the issue I was facing. It's strange that this wasn't a problem in the Python console in QGIS. – Benjamin Dec 5 '16 at 11:43
  • @Benjamin - Most welcome, glad it helped! You mean using single backslashes isn't a problem in the console? – Joseph Dec 5 '16 at 11:46
  • It wasn't when I tested the code in the console that's in the QGIS GUI – Benjamin Dec 5 '16 at 11:48
  • @Benjamin - Yeah I think QGIS is quite forgiving when it comes to little things like this and solves it automatically. Or atleast that's what I experienced several times =) – Joseph Dec 5 '16 at 11:51

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.