[GIS] Writing scripts that can call on both Arcpy and PyQGIS

arcgis-10.2arcpyimporterrorpyqgis

I have spent quite a bit of time looking for a clear answer this topic and have still been unable to really accomplish my goal of accessing PyQGIS in a stand alone script.

Parts of answers have been provided across many different questions such as:

Standalone applications using QGIS and environment variables

pyQgis in stand alone script, vector loading error

Writing standalone Python scripts using PyQGIS?

The most thourough Answer that I have found was provided by @gene here.

What I particularly am interested in, is being able to write scripts that can call on both Arcpy, and PyQGIS. I have set both PATH and PYTHONPATH system variables according to the PyQGIS cookbook documentation as:

 C:\OSGeo4W\apps\qgis\bin,%PATH%;C:\Python27\ArcGIS10.2\Lib\site-packages\PyQt4;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\

and

C:\OSGeo4W\apps\qgis\python; C:\OSGeo4W\apps\Python27\Lib\site-packages

Respectively.

I am starting with this script:

from qgis.core import *

QgsApplication.setPrefixPath("C:\OSGeo4W\bin\qgis.bat", True)
QgsApplication.initQgis()
# or your solution
# read a shapefile 
layer = QgsVectorLayer('H:\DATA\Airfields_AB.shp', 'Airfields', 'ogr')
layer.isValid()
True
# loop through layer 
for elem in layer.getFeatures():
    geom= elem.geometry()
    attr =elem.attributes()
    (processing)

I am looking to avoid batch scripts that set the appropriate settings, but rather call them from inside the Python script. The optimal scenario for me would be to use the IDLE in the ArcGIS 10.2 folder to run the preceding code. I am using a Windows 7 machine with ArcGIS 10.2 and QGIS 2.01.

Currently the results of this code is:

Traceback (most recent call last):
  File "F:\Users\...\PyQGIS_Test_01.py", line 1, in <module>
    from qgis.core import *
ImportError: DLL load failed: The specified module could not be found.

Best Answer

You will need to make sure your PATH environment variable includes the folder where the python dlls are located. Usually under [QGIS_install_folder]\apps\qgis\bin e.g.

C:\Program Files (x86)\QGIS Valmiera\apps\qgis\bin

Also have a look at Configure PyScripter to use with QGIS (and still use arcpy) on Windows Quite old post now, but should give you the basic idea of what needs to be setup

Related Question