2

I'm trying to learn to write standalone Python scrips for QGIS, but can't get past first base.

I'm using QGIS 2.18, installed with the OSgeo4W64 installer. I have modified my path as follows.

SET OSGEO4W64_ROOT=C:\OSGeo4W64
SET QGIS_PREFIX=%OSGEO4W64_ROOT%\apps\qgis
SET PATH=%PATH%;%QGIS_PREFIX%\bin
SET PYTHONPATH=%QGIS_PREFIX%\python;%PYTHONPATH%

I'm trying to run a script that begins:

import os, os.path, sys
from qgis.core import *
from qgis.gui import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *

I get the following error:

C:\Users\Steve\Documents\MEGAsync\Steve\Lex>lex.py
Traceback (most recent call last):
  File "C:\Users\Steve\Documents\MEGAsync\Steve\Lex\lex.py", line 3, in <module>
    from qgis.core import *
  File "C:\OSGeo4W64\apps\qgis\python\qgis\__init__.py", line 26, in <module>
    from qgis.PyQt import QtCore
  File "C:\OSGeo4W64\apps\qgis\python\qgis\PyQt\QtCore.py", line 26, in <module>
    import sip
ImportError: DLL load failed: %1 is not a valid Win32 application.

What am I doing wrong?

Steve
  • 361
  • 1
  • 5
  • Hi Joseph - thanks for that. I've tried implementing those steps by:
    1. opening the OSGeo4W shell
    2. running the batch file (which I modified to refer to my directory 'OSGeo4W64'

    3b. executing a python script containing 'from qgis import *'

    But it still gives the same 'DLL load failed' error.

    I can import the libraries manually (3a of the answer) if I enter the python interpreter in the OSGeo shell - but only if I use 'python-qgis' for the interpreter, not 'python'. And of course, importing them manually doesn't help with an external script.

    – Steve Nov 07 '16 at 22:28
  • It works if I use SET PATH=%OSGEO4W_ROOT%\bin;%QGIS_PREFIX%\bin; and SET PYTHONPATH=%QGIS_PREFIX%\python;%OSGEO4W_ROOT%\apps\Python27;. Only works in the OSGeo4W shell though, not at the standard command prompt, where it throws ImportError: No module named site – Steve Nov 08 '16 at 02:15

1 Answers1

1

Finally, all my problems went away with the following.

SET OSGEO4W_ROOT=C:\OSGeo4W64
SET QGIS_PREFIX=%OSGEO4W_ROOT%\apps\qgis
SET PATH=%OSGEO4W_ROOT%\bin;%QGIS_PREFIX%\bin;
SET PYTHONPATH=%QGIS_PREFIX%\python;%OSGEO4W_ROOT%\apps\Python27;%OSGEO4W_ROOT%\apps\Python27\Lib;
SET GDAL_DATA=C:\OSGeo4W64\share\epsg_csv\
python myfile.py
Steve
  • 361
  • 1
  • 5