The Python Console

The Python Console is a wonderful instrument to explore and learn PyQGIS. It's available in every QGIS installation and can be opened by selecting the Python Console voice in the Plugins menu.

The Python Console is a dockable interface, and like all dockable interfaces, you can change its position inside QGIS or separate it. You can try moving the console by dragging and dropping it.

The console is shown in this screenshot:

The Python Console

As you can see, the console is composed of a button toolbar marked by the red box. The bigger Python Console is marked by the upper-right red box and is where all the command results are shown, and finally a bottom command line, marked by the bottom-right red box, is where you can edit commands. The default position of these graphical components can vary with QGIS version.

Here, we describe how to test code interactively and explore the PyQGIS classes. However, we will not explain all the possibilities of the Python Console. These are well documented and you can find them at http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html#python-console.

Getting sample data

To continue experimenting with PyQGIS, we need a test dataset. The QGIS project has training material and sample data that we'll use in our snippet.

The QGIS sample data can be downloaded from http://qgis.org/downloads/data/.

My first PyQGIS code snippet

To break the ice, we will create our first PyQGIS code to show the unique ID of a selected layer loaded in QGIS:

  1. To start with, we will first load the layer, airports.shp, which is available in the shapefiles directory of qgis_sample_data.
  2. After it has been loaded successfully, select it in the list of layers; doing this will make it the active layer for QGIS.
  3. Then we get the reference of the layer object by writing the following line in the Python Console command line:
    layer = iface.activeLayer()
    
  4. After editing the code and hitting Return, the edited command code is shown in the console.
  5. The reference of the current active layer is archived in the variable named layer. Now, we can show the layer ID by typing the following code command in the command line after pressing Return:
    print layer.id()
    
  6. The output will display something similar to airports20141001174143539.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.137.17