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.

asked Dec 5, 2016 at 3:26

1 Answer 1

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

answered Dec 5, 2016 at 9:57
4
  • 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. Commented Dec 5, 2016 at 11:43
  • @Benjamin - Most welcome, glad it helped! You mean using single backslashes isn't a problem in the console? Commented Dec 5, 2016 at 11:46
  • It wasn't when I tested the code in the console that's in the QGIS GUI Commented Dec 5, 2016 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 =) Commented Dec 5, 2016 at 11:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.