I need to build an app to analyze some raster layers in QGIS.
I thought it was possible to just write code in python (2.7.6) (IDLE) and let it automatically open QGIS, load some layers, do a distance matrix, export that and load this file with python and use that information in the app.
Is something like this possible?
I have a mac running OSX10.9.1, using python 2.7.6 because I constantly got errors when using python 3.
-
2Did you try searching first? First hit on Google for "qgis python": qgis.org/en/docs/pyqgis_developer_cookbook/intro.htmlSnorfalorpagus– Snorfalorpagus2014年03月05日 17:32:18 +00:00Commented Mar 5, 2014 at 17:32
-
yes I did but at the bottom of that page you have the "Running Custom Applications" section but this one is only written for windows and linux. When I do the import qgis.core step, I also get the error message but I'm not finding how to get rid of it.Peter Vanvoorden– Peter Vanvoorden2014年03月05日 17:38:50 +00:00Commented Mar 5, 2014 at 17:38
-
This comment would be more useful as an answer, @Snorfalorpagus.Jeremy J– Jeremy J2014年03月05日 17:39:19 +00:00Commented Mar 5, 2014 at 17:39
1 Answer 1
As already been mentioned in GS exchange, the QGIS version of Kyng Chaos uses the standard Apple Python and the version 2.x (and not the 3.x, nor others Python implementation, Homebrew, Anaconda, etc.)
As indicated in the documentation, you must first add PyQGIS to the PYTHONPATH
I use here the Terminal application:
export PYTHONPATH=/Applications/Qgis.app/Contents/Resources/python
But you can put this line in the .Bash_profile file (you need to know the Unix part of Mac OS X).
After, follow the documentation:
Python
......
>>> from qgis.core import *
>>> QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS", True)
>>> QgsApplication.initQgis()
>>> # confirmation
>>> print QgsApplication.showSettings()
Application state:
QGIS_PREFIX_PATH env var:
Prefix: /Applications/QGIS.app/Contents/MacOS
Plugin Path: /Applications/QGIS.app/Contents/MacOS/../PlugIns/qgis
Package Data Path: /Applications/QGIS.app/Contents/MacOS/../Resources
Active Theme Name:
Active Theme Path: :/images/themes//
Default Theme Path: :/images/themes/default/
SVG Search Paths: /Applications/QGIS.app/Contents/MacOS/../Resources/svg/
User DB Path: /Applications/QGIS.app/Contents/MacOS/../Resources/resources/qgis.db
and you can use PyQGIS:
>>> layer = QgsVectorLayer('/Users/Shared/test.shp', 'test', 'ogr')
>>> layer.isValid()
True
>>> buffer_Shp = layer.buffer(10, 5)
>>> # and you can import also:
>>> import qgis.utils
>>> # and
>>> from qgis.gui import *
But you need PyQT4 if you want to use qgis.gui