Outdated version of the documentation. Find the latest one here.

はじめに

This document is intended to work both as a tutorial and a reference guide. While it does not list all possible use cases, it should give a good overview of the principal functionality.

Starting from 0.9 release, QGIS has optional scripting support using Python language. We’ve decided for Python as it’s one of the most favourite languages for scripting. PyQGIS bindings depend on SIP and PyQt4. The reason for using SIP instead of more widely used SWIG is that the whole QGIS code depends on Qt libraries. Python bindings for Qt (PyQt) are done also using SIP and this allows seamless integration of PyQGIS with PyQt.

There are several ways how to use Python bindings in QGIS desktop, they are covered in detail in the following sections:

  • automatically run Python code when QGIS starts
  • issue commands in Python console within QGIS
  • create and use plugins in Python
  • create custom applications based on QGIS API

Python bindings are also available for QGIS Server:

  • starting from 2.8 release, Python plugins are also available on QGIS Server (see Server Python Plugins)
  • starting from 2.11 version (Master at 2015-08-11), QGIS Server library has Python bindings that can be used to embed QGIS Server into a Python application.

There is a complete QGIS API reference that documents the classes from the QGIS libraries. Pythonic QGIS API is nearly identical to the API in C++.

A good resource when dealing with plugins is to download some plugins from plugin repository and examine their code. Also, the python/plugins/ folder in your QGIS installation contains some plugin that you can use to learn how to develop such plugin and how to perform some of the most common tasks.

Run Python code when QGIS starts

QGISを起動するたびにPythonコードを実行するには、2つの異なる方法があります。

PYQGIS_STARTUP環境変数

You can run Python code just before QGIS initialization completes by setting the PYQGIS_STARTUP environment variable to the path of an existing Python file.

This method is something you will probably rarely need, but worth mentioning here because it is one of the several ways to run Python code within QGIS and because this code will run before QGIS initialization is complete. This method is very useful for cleaning sys.path, which may have undesireable paths, or for isolating/loading the initial environ without requiring a virt env, e.g. homebrew or MacPorts installs on Mac.

startup.py ファイル

Every time QGIS starts, the user’s Python home directory (usually: .qgis2/python) is searched for a file named startup.py, if that file exists, it is executed by the embedded Python interpreter.

Python Console

For scripting, it is possible to take advantage of integrated Python console. It can be opened from menu: Plugins ‣ Python Console. The console opens as a non-modal utility window:

../../_images/console.png

QGIS Python コンソール

The screenshot above illustrates how to get the layer currently selected in the layer list, show its ID and optionally, if it is a vector layer, show the feature count. For interaction with QGIS environment, there is a iface variable, which is an instance of QgsInterface. This interface allows access to the map canvas, menus, toolbars and other parts of the QGIS application.

For convenience of the user, the following statements are executed when the console is started (in future it will be possible to set further initial commands)

from qgis.core import *
import qgis.utils

For those which use the console often, it may be useful to set a shortcut for triggering the console (within menu Settings ‣ Configure shortcuts...)

Python プラグイン

QGIS allows enhancement of its functionality using plugins. This was originally possible only with C++ language. With the addition of Python support to QGIS, it is also possible to use plugins written in Python. The main advantage over C++ plugins is its simplicity of distribution (no compiling for each platform needed) and easier development.

Many plugins covering various functionality have been written since the introduction of Python support. The plugin installer allows users to easily fetch, upgrade and remove Python plugins. See the Python Plugin Repositories page for various sources of plugins.

Pythonでプラグインを作るのはとても簡単です。詳細は プラグイン を見てください。

ノート

Python plugins are also available in QGIS server (OGCデータサーバーとしてのQGIS), see QGISサーバーのPythonプラグイン for further details.

Python アプリケーション

Often when processing some GIS data, it is handy to create some scripts for automating the process instead of doing the same task again and again. With PyQGIS, this is perfectly possible — import the qgis.core module, initialize it and you are ready for the processing.

Or you may want to create an interactive application that uses some GIS functionality — measure some data, export a map in PDF or any other functionality. The qgis.gui module additionally brings various GUI components, most notably the map canvas widget that can be very easily incorporated into the application with support for zooming, panning and/or any further custom map tools.

PyQGIS custom applications or standalone scripts must be configured to locate the QGIS resources such as projection information, providers for reading vector and raster layers, etc. QGIS Resources are initialized by adding a few lines to the beginning of your application or script. The code to initialize QGIS for custom applications and standalone scripts is similar, but examples of each are provided below.

Note: do not use qgis.py as a name for your test script — Python will not be able to import the bindings as the script’s name will shadow them.

スタンドアロンスクリプトでPyQGISを使用する

スタンドアロンスクリプトを起動するには、次のコードのようなスクリプトの先頭でQGISのリソースを初期化します。

from qgis.core import *

# supply path to qgis install location
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)

# create a reference to the QgsApplication, setting the
# second argument to False disables the GUI
qgs = QgsApplication([], False)

# load providers
qgs.initQgis()

# Write your code here to load some layers, use processing algorithms, etc.

# When your script is complete, call exitQgis() to remove the provider and
# layer registries from memory
qgs.exitQgis()

qgis.core モジュールをインポートし、それからプレフィックスパスを設定することから始めます。プレフィックスパスとはQGISがシステムにインストールされている場所です。これはこのスクリプト中で setPrefixPath メソッドを呼び出すことで設定されます。 setPrefixPath の第2引数は true に設定されています。これはデフォルトのパスが使用されているかどうかを制御します。

QGISのインストールパスは、プラットフォームによって異なります。お使いのシステムに対するパスを見つける最も簡単な方法は、QGIS内から Python Console を使用し、実行している QgsApplication.prefixPath() からの出力を見ることです。

プレフィックスパスを設定した後は QgsApplication 変数に qgs への参照を保存します。今書いているのはスタンドアロンスクリプトですので、GUIを使用する予定がないことを示すために第二引数に False を設定します。 QgsApplication が設定されると、 qgs.initQgis() メソッドを呼び出すことでQGISデータプロバイダーとレイヤーのレジストリを読み込みます。QGISが初期化されると、残りのスクリプトを記述する準備が整いました。最後に、 qgs.exitQgis() を呼び出して、メモリからデータプロバイダーとレイヤーのレジストリを削除しておしまいです。

カスタムアプリケーションでPyQGISを使用する

スタンドアロンスクリプトでPyQGISを使用する とカスタムPyQGISアプリケーションの唯一の違いは QgsApplication をインスタンス化する際の二番目の引数です。 TrueFalse の代わりに渡し、GUIを使用することを計画していると示してください。

from qgis.core import *

# supply path to qgis install location
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)

# create a reference to the QgsApplication
# setting the second argument to True enables the GUI, which we need to do
# since this is a custom application
qgs = QgsApplication([], True)

# load providers
qgs.initQgis()

# Write your code here to load some layers, use processing algorithms, etc.

# When your script is complete, call exitQgis() to remove the provider and
# layer registries from memory
qgs.exitQgis()

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 :-)

カスタムアプリケーションを実行する

QGISのライブラリとPythonモジュールが一般的な場所に置かれて無ければ、システムに適切な場所を伝える必要があるでしょう — そうしないとPythonはエラーを吐きます:

>>> import qgis.core
ImportError: No module named qgis.core

This can be fixed by setting the PYTHONPATH environment variable. In the following commands, qgispath should be replaced with your actual QGIS installation path:

  • on Linux: export PYTHONPATH=/qgispath/share/qgis/python
  • on Windows: set PYTHONPATH=c:\qgispath\python

The path to the PyQGIS modules is now known, however they depend on qgis_core and qgis_gui libraries (the Python modules serve only as wrappers). Path to these libraries is typically unknown for the operating system, so you get an import error again (the message might vary depending on the system):

>>> import qgis.core
ImportError: libqgis_core.so.1.5.0: cannot open shared object file: No such file or directory

QGISライブラリが存在するディレクトリを動的リンカのパスに追加することでこれを修正します:

  • on Linux: export LD_LIBRARY_PATH=/qgispath/lib
  • on Windows: set PATH=C:\qgispath;%PATH%

これらのコマンドはブートストラップスクリプトに入れておくことができます。PyQGISを使ったカスタムアプリケーションを配布するには、これらの二つの方法が可能でしょう:

  • require user to install QGIS on his platform prior to installing your application. The application installer should look for default locations of QGIS libraries and allow user to set the path if not found. This approach has the advantage of being simpler, however it requires user to do more steps.
  • アプリケーションと一緒にQGISのパッケージを配布する方法です。アプリケーションのリリースにはいろいろやることがあるし、パッケージも大きくなりますが、ユーザーを追加ソフトウェアをダウンロードをしてインストールする負荷から避けられるでしょう。

これらのモデルは組み合わせることができます - Windows と Mac OSではスタンドアローンアプリケーションとして配布をして、LinuxではQGISのインストールをユーザーとユーザーが使っているパッケージマネージャに任せるとか。