Friday 20 December 2019

pyqgis - Opening vector layer in QGIS Python standalone application?


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.



Answer



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...