PyQGIS – How to Write Standalone Python Scripts Using PyQGIS

pyqgis

I've been learning how to use the Python Console in QGIS using references from qgisworkshop.org. I'm familiar with writing standalone scripts in ArcGIS and want to learn how to do the same with QGIS.

For example, in ArcGIS 10 a simple standalone python script would be:

import arcpy 

setFolder = ''

doProcess

I understand how to do this using the python console in QGIS, but I have not managed to find an example to perform the same steps using a standalone script. I suspect I've just been unlucky with my searching though. Are there any clear examples of how to do this online?

Best Answer

I haven't written stand-alone scripts based on QGIS API yet, but the PyQGIS cookbook uses the following initialization:

First of all you have to import qgis module, set QGIS path where to search for resources — database of projections, providers etc. When you set prefix path with second argument set as True, QGIS will initialize all paths with standard dir under the prefix directory. Calling initQgis() function is important to let QGIS search for the available providers.

from qgis.core import *

# supply path to where is your qgis installed
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)

# load providers
QgsApplication.initQgis()

Now you can work with QGIS API - load layers and do some processing or fire up a GUI with a map canvas. The possibilities are endless :-)

When you are done with using QGIS library, call exitQgis() to make sure that everything is cleaned up (e.g. clear map layer registry and delete layers):

QgsApplication.exitQgis()