18

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?

1 Answer 1

15

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()
4
  • 1
    Thanks @underdark - that is helpful. I have found it non-trivial to get from qgis.core import * to work on OSX, so I plan to ask a new question on this topic.
    – djq
    Commented Jul 22, 2012 at 19:43
  • Sorry to tag another question on here, but is there any online documentation of the qgis module? All I can find is a reference to it being similar to the c++ docs, but no actual link to the python docs.
    – djq
    Commented Jul 24, 2012 at 15:48
  • Python specifics are in the pyQGIS Cookbook. Otherwise you can rely on the normal C++ API docs - it's not just similar, imho it's same.
    – underdark
    Commented Jul 24, 2012 at 16:19
  • For ubuntu user refer: gis.stackexchange.com/questions/52919/… for installation path. (it's "/usr")
    – Mr Purple
    Commented Jul 3, 2015 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.