[GIS] import qgis.core problem with QgsFeature and QgsGeometry

importpythonqgis

I've tried several previous answers to similar questions – no luck.

I run Win7. I installed QGIS 2.2.0 using the OSGeo4W 32-bit installer.

Problem 1) from qgis.core import * failed.
Solution 1) After everything related to setting Path and PYTHONPATH variables failed, I had to copy C:\OSGeo4W\apps\qgis\python\qgis to C:\Python27\Lib\site-packages (and yes, including C:\OSGeo4W\apps\qgis\python\qgis in both Path and PYTHONPATH did NOT work).

Problem 2) The above approach got the qgis.core import started, but resulted in the following error message related to QgsFeature and QgsGeometry:

Traceback (most recent call last):
  File "D:\Research\inhaca\OBIA\model_script.py", line 1, in <module>
    from qgis.core import *
  File "C:\Python27\lib\site-packages\qgis\__init__.py", line 35, in <module>
    from qgis.core import QgsFeature, QgsGeometry
ImportError: DLL load failed: The specified module could not be found.

Now I'm lost. I tried copying all files from C:\OSGeo4W\apps\qgis\include and C:\OSGeo4W\apps\qgis\lib to the respective (include and Lib) folders in C:\Python27 – still didn't work. I'm fumbling in the dark here, any pointers?

Best Answer

You need to create a batch file to bootstrap your Python file that setups the correct environment. This is the one I use for all of my standalone QGIS apps:

REM Change OSGEO4W_ROOT to point to the base install folder
SET OSGEO4W_ROOT=C:\OSGeo4W
SET QGISNAME=qgis
SET QGIS=%OSGEO4W_ROOT%\apps\%QGISNAME%
set QGIS_PREFIX_PATH=%QGIS%

REM Python Setup
set PATH=%OSGEO4W_ROOT%\bin;%QGIS%\bin;%PATH%
SET PYTHONHOME=%OSGEO4W_ROOT%\apps\Python27
set PYTHONPATH=%QGIS%\python;%PYTHONPATH%

python yourscript.py

The QGISNAME variable is only so I can swap between release qgis and dev QGIS for testing, remove if not needed.

Related Question