Problem with import qgis.core when writing a stand-alone PyQGIS script

If you have installed QGIS via OSGeo4W, I suggest you to follow this work flow (I've just tested it on Windows 7):

  1. Open the OSGeo4W Shell. Start->All programs->OSGeo4W->OSGeo4W Shell.

  2. Set environment variables. My preferred way is to execute this bat file (updated 2016.11.03: this bat file) from the OSGeo4W Shell. As you can see, the file sets environment variables in this way:

    set PYTHONPATH=%OSGEO4W_ROOT%\\apps\\qgis\\python
    set PATH=%OSGEO4W_ROOT%\\apps\\qgis\\bin;%PATH%
    

    Of course, you need to check by yourself that those paths exist in your OS and adjust them if necessary.

    So, download the .bat file and execute it by accessing it from the OSGeo4W Shell and pressing ENTER.

    enter image description here

  3. Import PyQGIS libraries by one of the following methods:

    a. Enter the Python interpreter. Run python in the OSGeo4W Shell and import the libraries manually.

    enter image description here

    b. Execute a Python script. Run python my_pyqgis_script.py in the OSGeo4W Shell. I'd start with a very simple one.

    enter image description here

The work flow was posted (in Spanish) several years ago in GeoTux and still works. As you can see, I do not include environment variables in the Python script, but set them in the OSGeo4W Shell.


I've just been wrestling with a similar problem, and noticed a batch file in the OSGeo4W\bin folder called python-qgis.bat. This is part of an OSGeo4W package based install of QGIS 2.18.15 x64 on Windows 10.

When executed, this batch file opens the Python interpreter. import qgis successfully runs from within.

This batch file contains the line (as noted by Germán Carrillo in his original answer):

set PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis\python;%PYTHONPATH%

just before the python interpreter is launched.