New Version of the QGIS Script Runner Plugin

The Script Runner plugin allows you to manage and execute a collection of scripts in QGIS to automate tasks and perform custom processing.

Version 0.6 of Script Runner has been released and includes these changes:

  • Arguments can be passed to a script using keyword arguments
  • Script output is logged to the Script Runner window
  • Script output can be logged to disk
  • Preferences dialog allows control of output and logging options
  • Exceptions in scripts are displayed without interfering with console/logging output
  • Context menu (right-click) to access script functions
  • Edit script function uses system default editor or one you specify in preferences

For a basic introduction to Script Runner see this post: Script Runner: A Plugin to Run Python Scripts in QGIS

Working with Scripts

Adding Scripts

To run a script, you must add it to Script Runner using the Add Script tool on the toolbar. Select the script from the file dialog to add it to a list in the left panel. The list of scripts is persisted between uses of QGIS.

Running a Script

To run a script, select it from your list of scripts and click the Run tool. Output from the script will be displayed in the Script Runner console

Remove a Script

You can remove a script by selecting it from the list and clicking the Remove Script tool. This just removes it from the list; it does nothing to the script file on disk.

Script Information

Clicking the Info tool will populate the Info and Source tabs in the panel on the right. The Info tab contains the docstring from your module and then a list of the classes, methods, and functions found in the script. Having a proper docstring at the head of your script will help you determine the purpose of script.

At version 0.6 the Info tool is only needed if you have disabled automatic display of info/source (see Preferences).

Viewing the Source

You can view the source of the script on the Source tab. This allows you to quickly confirm that you are using the right script and it does what you think it will.

New Features

Version 0.6 implements a number of new features.

Passing Arguments to a Script

You can pass arguments to your script using keywords. Your run_script function must have two arguments:

  def run_script(iface, **args):
  

Running your script is done using the Run script with arguments tool. This prompts you to enter your argument(s) in a key=value format:

Argument_dialog

All strings must be quoted and multiple arguments should be separated by a comma.

When your script is run, the arguments are contained in args, which is a Python dict. In the example above, you could access them like this:

  my_path = args['path']
  my_buffer_size = args['buffer_size']
  

Scripts that accept keyword arguments are displayed in the list with two asterisks appended to their name:

arg_scripts

See Passing Arguments for a complete example.

Output Console

All print statements in your script will be directed to the Script Runner console. In addition, any tracebacks from exceptions will be displayed there, as well as in a popup dialog.

Printing messages to the console can be useful for both development and status updates in long running scripts. You can clear the console using the Clear Console tool. There is also an option in Preferences to clear the console each time a script is run.

Logging to Disk

You can choose to log everything that goes to the output console to disk. Use the Preferences dialog to setup the directory where the scriptrunner.log will be written.

Editing a Script

You can open the selected script in an external editor by right-clicking on it and choosing Edit script in external editor from the popup menu. The default system editor for .py files will be used to open the script. In Preferences, you can specify a different editor by entering the full path to the executable.

Preferences

The Preferences dialog allows you to set the following options:

Script_Runner_Preferences

Script Examples

Here are three script examples: a simple script that has only a run_script function, one that uses a Python class, and one that passes keyword arguments.

Simple Script

This simple script contains only a run_script function:

    """ Load a layer and change the fill color to red. """
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from qgis.core import *
    from qgis.gui import *
 

    def run_script(iface):
        mapreg = QgsMapLayerRegistry.instance()
        mapreg.removeAllMapLayers()
        wb = QgsVectorLayer('/data/world_borders.shp', 'world_borders', 'ogr')
        mapreg.instance().addMapLayer(wb)
        renderer = wb.rendererV2()
        symb = renderer.symbol()
        symb.setColor(QColor(Qt.red))
        wb.setCacheImage(None)
        wb.triggerRepaint()
        iface.refreshLegend(wb)

When executed by Script Runner, the script removes any layers currently on the map, then loads the world_borders shapefile, sets its fill color to red, and updates the map canvas and the legend. The run_script function does all the work. You could expand this script by adding additional functions that are called from run_script.

A Script with a Class

This script uses a class that is initialized from the run_script function to load some layers:

    """Load all shapefiles in a given directory.  """
    from glob import glob
    from os import path
 
    from qgis.core import *
    from qgis.gui import *
    import qgis.utils
 
    class Loader:
        def __init__(self, iface):
            """Initialize using the qgis.utils.iface
            object passed from the console.
            """
 
            self.iface = qgis.utils.iface
 
        def load_shapefiles(self, shp_path):
            """Load all shapefiles found in shp_path"""
            print "Loading shapes from %s" % path.join(shp_path, "*.shp")
            shps = glob(path.join(shp_path, "*.shp"))
            for shp in shps:
                (shpdir, shpfile) = path.split(shp)
                print "Loading %s" % shpfile
                lyr = QgsVectorLayer(shp, shpfile, 'ogr')
                QgsMapLayerRegistry.instance().addMapLayer(lyr)
 
    def run_script(iface):
        ldr = Loader(iface)
        print "Loading all shapefiles in /qgis_sample_data/vmap0_shapefiles"
        ldr.load_shapefiles('/qgis_sample_data/vmap0_shapefiles')

In this example, the run_script function creates an instance (ldr) of a class named Loader that is defined in the same source file. It then calls a method in the Loader class named load_shapefiles to do something useful—in this case, load all the shapefiles in a specified directory.

Passing Arguments

This script illustrates passing an argument (a path) to load all shapefiles in a directory:

    """Load all shapefiles in a given directory."""
    from glob import glob
    from os import path
    from qgis.core import *
    from qgis.gui import *
    import qgis.utils
 
 
    class Loader:
        def __init__(self, iface):
            """Initialize using the qgis.utils.iface 
            object passed from the console.
 
            """
            self.iface = qgis.utils.iface

        def load_shapefiles(self, shp_path):
            """Load all shapefiles found in shp_path"""
            print "Loading shapes from %s" % path.join(shp_path, "*.shp")
            shps = glob(path.join(shp_path, "*.shp"))
            for shp in shps:
                (shpdir, shpfile) = path.split(shp)
                print "Loading %s" % shpfile
                lyr = QgsVectorLayer(shp, shpfile, 'ogr')
                QgsMapLayerRegistry.instance().addMapLayer(lyr)

    def run_script(iface, **args):
        ldr = Loader(iface)
        print "Loading all shapefiles in %s" % args['path']
        ldr.load_shapefiles(args['path'])

Lines 29 and 30 illustrate using the passed argument to print a message to the console and call the method to add the shapefiles to the map.

Final Word

The script examples are minimalistic—they don’t do error checking in a number of places, such as checking to see if a QgsVectorLayer is valid or if needed arguments were actually passed to the script. Don’t take the scripts as examples of complete, solid code.

Comments on this post are welcome, as are bug reports. The link to the bug tracker for Script Runner can be found in the About box, along with the link to the code repository and my email address.