简体   繁体   English

Python QGIS:图层无法加载

[英]Python QGIS: Layer failed to load

I am trying to load a QGIS vector layer from a SHP file in Python. 我正在尝试从Python中的SHP文件加载QGIS矢量层。 Whenever I run it, layer.isValid() always returns False (or "Layer is not valid!" in this case). 每当我运行它时,layer.isValid()始终返回False(在这种情况下为“ Layer无效!”)。 I'm not sure what I am doing wrong here, or if I have instantiated the QgsVectorLayer variable incorrectly. 我不确定在这里做错了什么,或者不确定是否错误地实例化了QgsVectorLayer变量。

import sys
import os
from qgis.core import *
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches


QgsApplication.setPrefixPath("/usr", True)
qgs = QgsApplication(sys.argv, False)
qgs.initQgis()

layer=QgsVectorLayer("/Users/ANON/Desktop/MassShapeFiles/MassachusettsTownBoundaries.shp", "MassachusettsTownBoundaries", "ogr")
providers = QgsProviderRegistry.instance().providerList()
for provider in providers:
    print provider
if not layer.isValid():
    print "Layer failed to load!"
provider = layer.dataProvider()

Thank you! 谢谢!

I think your path is malformed. 我认为您的路径格式错误。 Looking to path structure I assume you are in a windows system, so your windows path should be: 寻找路径结构,我假设您在Windows系统中,因此Windows路径应为:

"\\Users\\ANON\\Desktop\\MassShapeFiles\\MassachusettsTownBoundaries.shp"

with double backslash notation to avoid python misunderstandings 使用双反斜杠表示法以避免python的误解

you are in windows system. 您在Windows系统中。 but you have used qgis prefix path as linux system. 但是您已经将qgis前缀路径用作linux系统。 Get the proper qgis prefix path from qgis python console by printing QgsApplication.showSettings. 通过打印QgsApplication.showSettings从qgis python控制台获取正确的qgis前缀路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM