pyqgis python qgis sysadmin

Installing Third-party Python Modules in QGIS (Windows)

We’ve recently been developing a client plugin for forest management which relies on the Python SQLAlchemy module. When I installed the latest version of my colleague’s work I got a Python traceback error about a missing Python module (SQLAlchemy).

This blog is more of a note to myself for future reference of how to install third-party modules in QGIS’ Python environment.

The Problem

Installing third-party modules in Windows is usually quite straight-forward, either download an installer (which will find the Python environment from the registry) or use easy_install from the Python setuptools.

The problem is that QGIS ships with its own Python installation that these methods cannot easily add to.

(Don’t get me wrong – I like the fact that each QGIS instance has its own Python environment as it keeps each version very self-contained).

The Method

So here’s the method I successfully used to install SQLAlchemy (which I’ll use here to install the lxml module):

  • Click Start
  • Type QGIS
  • Wait for the QGIS version / instance you want to modify to appear:

  • Right-click it, select Run as administrator

  • In QGIS, select Python Console from the Plugins menu
  • Download ez_setup.py from here.
  • Run the following code on the python console in QGIS:
1
2
3
4
5
6
7
8
9
10
11
12
from subprocess import call
# Replace the path below to the location of ez_setup.py that 
# you just downloaded
call(['python', r'C:\Users\Pete\Downloads\ez_setup.py'])

# This will install *setuptools* which is a package manager
# The previous command should return 0 on success

# Replace lxml with the package you wish to install
call(['easy_install', 'lxml'])

# Again this will return 0 on success
  • Restart QGIS (normally, not using the Run as administrator option)

The new module should now be available, we can test this (again on the Python console in QGIS):

1
import lxml

That’s it!