
QGIS Python Programming Cookbook, Second Edition
By :

The QGIS Python Script Runner plugin provides a middle ground for QGIS automation, between the interactive console and the overhead of plugins. It provides a script management dialog that allows you to easily load, create, edit, and run scripts for large-scale QGIS automation.
Install the Script Runner plugin using the QGIS plugin manager. Then, run the plugin from the Plugin menu to open the Script Runner dialog. Configure a default editor to edit the scripts using the following steps:
from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * from qgis.gui import * def run_script(iface): layer = QgsVectorLayer('Polygon?crs=epsg:4326', 'Mississippi', "memory") pr = layer.dataProvider() poly = QgsFeature() geom = QgsGeometry.fromWkt("""POLYGON ((-88.82 34.99, -88.09 34.89, -88.39 30.34, -89.57 30.18, -89.73 31, -91.63 30.99, -90.87 32.37, -91.23 33.44, -90.93 34.23, -90.30 34.99, -88.82 34.99))""") poly.setGeometry(geom) pr.addFeatures([poly]) layer.updateExtents() QgsMapLayerRegistry.instance().addMapLayers([layer])
Script Runner is a simple but powerful idea. It allows you to build a library of automation scripts and use them from within QGIS without the overhead of building a plugin or a standalone application. All the Python and system path variables are set correctly and inherited from QGIS; however, you must still import the QGIS and Qt libraries.
The Script Runner plugin makes managing lots of scripts easier. But there is also a script editor built into the PyQGIS console. This editor is a panel in the QGIS interface that you can use to create, edit, and run scripts. You can trigger the editor using the fourth icon from the left on the PyQGIS console toolbar.