2

I've been struggling with a standalone script in PyCharm, trying to add a vector layer. I've set up PyCharm with Python3.7 to work with QGIS3 using: http://spatialgalaxy.net/2014/10/09/a-quick-guide-to-getting-started-with-pyqgis-on-windows/#ide-example. I've tried tweaking paths in the bat file and script itself based on various posts to no avail.

At this point I am at a loss. I am new to both QGIS and Python.

Below I have provided all code and output. For reference, I am on a Windows 8 laptop.

Script:

import sys
import os

sys.path.append("C:/OSGeo4W64/apps/qgis/python/")
sys.path.append("C:/OSGeo4W64/apps/qgis/python/plugins")

# set path because apparently bat file didn't?
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'C:/OSGeo4W64/apps/Qt5/plugins'

from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

print("Import successful")

# Initialize QGIS Application
qgs = QgsApplication([], False)
QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
QgsApplication.initQgis()

print("QGIS initialized")

pathto = "C:/Users/USER/Documents/Research/bufftest.shp"
layer = QgsVectorLayer(pathto, "bufftest", "ogr")
if not layer.isValid():
    print("Layer fail!")

# Valid file?
print("File Path points to a file: ", os.path.isfile(pathto))

# Valid layer?
print("Output of layer.isValid(): ", layer.isValid())

qgs.exitQgis()

Bat file:

@echo off
SET OSGEO4W_ROOT=C:\OSGeo4W64
call "%OSGEO4W_ROOT%"\bin\o4w_env.bat
call "%OSGEO4W_ROOT%"\bin\qt5_env.bat
call "%OSGEO4W_ROOT%"\bin\py3_env.bat
@echo off
path %PATH%;%OSGEO4W_ROOT%\apps\qgis\bin
path %PATH%;C:\OSGeo4W64\apps\Qt5\bin
path %PATH%;C:\OSGeo4W64\apps\Python37\Scripts

set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\qgis\python
set PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
set QT_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\qgis\qtplugins;%OSGEO4W_ROOT%\apps\qt5\plugins

start "PyCharm aware of Quantum GIS" /B "C:\Program Files\JetBrains\PyCharm Community Edition 2018.3.1\bin\pycharm64.exe"

Debug output:

Import successful
QGIS initialized
Layer fail!
File Path points to a file: True
Output of layer.isValid(): False
sys:1: ResourceWarning: unclosed family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 57568), raddr=('127.0.0.1', 57566)>

Process finished with exit code 0


1 Answer 1

1

Found a solution here: PyQGIS QgsVectorLayer() Loading Invalid Layer in Standalone Python Script?

Just added the following line:

os.environ['QGIS_PREFIX_PATH'] = 'C:/OSGeo4W64/apps/qgis'

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.