How to run a simple python script for QGIS from outside (e.g. Sublime Text)?

You can't get a reference to the iface object here because it doesn't exist in this context. The iface (QgisInterface) object is a convenience object for plugins, or scripts running inside QGIS, to access the main objects e.g. the map canvas, legend, composer, etc, and only exists when the main application is running.

When you create a standalone Python script using the QGIS APIs none of this stuff exists because you are making your own mapping application.

There are three different situations:

  1. A QGIS plugin
  2. A script that runs inside QGIS (not a plugin) for automation
  3. Standalone app using QGIS APIs

1. and 2. have access to iface, the last one doesn't.

For 3 if you want to create a script that opens a layer in a map canvas you would do this after QgsApplication.initQgis()

map = QgsMapCanavs()
layer = QgsVectoryLayer('path.shp','myshapefile','ogr')
map.setLayerSet([layer])

However if you are really looking for something like 2 then you can just write this in your script editor

from qgis.core import *
from qgis.gui import *
import qgis.utils

qgis.utils.iface.activeLayer()

but this has to be run inside QGIS for qgis.utils to work. That can be done by putting the script on PATH and running import scriptname in the Python console or by using the ScriptRunner plugin.

Note the following isn't QGIS yet

There is a number 4 that hasn't been added yet, and hopefully will be in the future, and that is the option to run QGIS with a commandline arg to say run this code.

For example:

qgis --code=mycodefile.py

Plugin logging (version 1.8)

You can use the QgsMessageLog class to log information to the QGIS log window. The yellow exclamation mark in the bottom right corner.

from qgis.core import *
log = lambda m: QgsMessageLog.logMessage(m,'My Plugin') 
log('My message')

or without using lambda

QgsMessageLog.logMessage('My message', 'My Plugin')

I prefer the lambda based one as it is shorter and less typing any time you want to log something.


I think Nathan W's answer is out of date. I was able to run QGIS (version 2.6) python scripts from the command line (Nathan's option 4) using the following commands.

man qgis
qgis -nologo --project /path/foo.qgs --code /path/foo.py

Update for Nathan's option 4: (Windows, QGIS 2.18 Las Palmas)

To print QGIS help document,

qgis --help

To open QGIS, load a project, then, run a python script.

qgis --nologo --project c:/path/to/projfile.qgs --code c:/path/to/code.py

These commands should run on OSGeo4W Shell without problems.

Tags:

Pyqgis