3

I'm currently trying to translate the tasks I performed using Qgis (3.16.5) into a Python (Spyder) script, such that I will be able to perform these tasks on multiple files more easily.

However, I'm experiencing difficulties importing Qgis into Spyder. First, I received an error. After looking on internet, I found many topics related to this and I tried most of them.

Most of them were related to changing the PYTHONPATH and PATHs. I ended up with the script below: '''

@echo off
  SET OSGEO4W_ROOT=C:\OSGeo4W64
  call "%OSGEO4W_ROOT%"\bin\o4w_env.bat
  call "%OSGEO4W_ROOT%"\apps\grass\grass78\etc\env.bat
  @echo off
  path %PATH%;%OSGEO4W_ROOT%\apps\qgis\bin
  path %PATH%;%OSGEO4W_ROOT%\apps\grass\grass78\lib

  set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\qgis\python;
  set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\Python27\Lib\site-packages
  cmd.exe

However, I now get a new error: "DLL load failed while importing _core: Cannot find procedure" and still cannot import qgis.core. I tried this code both with OSGeo4W64 and with a Qgis version downloaded without OSGeo4W64.

How can I import the Qgis.core?

1 Answer 1

2

I'm somewhat confused that you have a recent QGIS (3.16.5), but that you're starting a Python 2.7? QGIS 3 uses Python 3, not 2.7 and it won't work.

At any rate, in your QGIS installation, you'll find some batch files, in my case it's this one c:\Program Files\QGIS 3.18\bin\py3_env.bat and python-qgis.bat.

So open your command line, and run:

cd c:\Program Files\QGIS 3.18\bin
CALL py3_env.bat
CALL python-qgis.bat

This'll start the QGIS interpreter, I can succesfully import qgis.core here.

c:\Program Files\QGIS 3.18\bin>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import qgis.core
>>> exit()

You can check whether it's starting the right python now by e.g. running:

where python

This should return the QGIS python as its first entry:

c:\Program Files\QGIS 3.18\apps\Python3.7\python.exe

Now, you could try starting Spyder (just run spyder in the command line). However, it has to be installed for this QGIS Python interpreter speficically. I think the default QGIS installation by default comes with pip, if you install via OSGeo4W, see: Do not have pip for my QGIS Python.

Note, however, that this is somewhat hap-hazard: QGIS and Spyder have a shared dependency in (Py)Qt and they might e.g. demand different versions.

If you run into trouble, you could try using a (non-Qt) editor/IDE like Visual Studio Code (again, probably start it after setting all the environmental variables right with the batch files mentioned above), or possibly something from jupyter.

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.