Using the console

While you briefly used the QGIS Console in the previous chapter, it is worth examining the QGIS Console window in more detail, so that you are aware of the various features that are available.

If you don't already have it open, choose the Python Console item from the Plugins menu to open the console. The following screenshot shows the various parts of the console window:

Using the console

Let's take a closer look at these various parts:

  • The Clear console button wipes out the contents of the interpreter log
  • The Import Class pop up contains shortcuts to import some commonly-used PyQGIS classes
    Using the console

    These are equivalent to typing import Processing, from PyQt4.QtCore import *, and from PyQt4.QtGui import *.

  • The Run command button simply executes the command you have typed in the Python shell field

    Note

    Of course, you can also run the entered command by pressing the Return key, so this command is only useful if you really want to run a command using the mouse.

  • The Show editor button shows or hides the built-in source code editor. We'll look at this shortly
  • The Settings button displays the console's Settings window, allowing you to customize the way the console looks and behaves
  • The Help button brings up the built-in help viewer page, which contains useful information about how to use the console
  • The Python Shell field is where you type your Python commands and other input
  • The Interpreter Log shows a complete history of the commands you have typed and the Python interpreter's output

As we've already seen, you can type Python commands in the shell and press the Return key to execute them. The commands you type, along with the Python interpreter's output, appear in the Interpreter Log.

The Python Shell has been designed to make it easier to work with Python interactively. The following features are currently supported:

  • Pressing the up and down arrow keys will move through the command history, making it easy to re-enter the Python commands you typed earlier.
  • You can display a list of previously-entered commands by pressing Ctrl + Shift + Space (command + Shift + Space on Mac).
  • If you select some text in the Interpreter Log, you can use the Enter Selected command to move that text to the shell and execute it. This command is available in the console's pop-up menu, or it can be accessed by pressing Ctrl + E (command + E if you are running Mac OS X).
  • The Python Shell supports auto-completion. As you type, a pop-up menu appears, showing you the matching class, function, and method names within the PyQGIS and PyQt APIs. You can then press the up and down arrow keys to select the exact name you want, and press the Tab key to select it.
  • When you type an opening parenthesis, the console automatically enters the closing parenthesis for you. You can turn this off by using the Settings window if you wish.
  • When you type from XXX, the console enters the word import for you automatically. Once again, you can turn this off in the Settings window if you don't like this behavior.
  • When you type the opening parenthesis for a function or method, the C++ signature for that function or method will be displayed. Despite being in C++ format, this tells you which parameters are expected and the type of value being returned.
  • You can type _api into the shell; your web browser will open the PyQGIS API reference documentation. Similarly, if you type _pyqgis, your web browser will display the PyQGIS Developer Cookbook.

While typing commands into the Python Shell is a useful way of exploring the QGIS Python libraries, and is good for one-off commands, it quickly gets tedious if you have to type multiple lines of Python text or repeat the same set of commands over and over. After all, this is why we store Python code in .py files and execute them, rather than just typing everything into the Python command-line interface.

The QGIS Console comes with its own editor, allowing you to write Python scripts and execute them directly within the console. Let's take a quick look at how this works.

With the QGIS Console open, click on the Show Editor icon (Using the console). The console window will be split in half, with the Python source code editor now taking up the right-hand side of the window:

Using the console

The various toolbar icons provide standard editing behavior such as loading and saving files, copying and pasting text, checking syntax, and executing your script:

Using the console

You'll probably want to memorize the top three icons as there are currently no keyboard shortcuts to open and save Python scripts.

Let's use the console editor to create a simple Python program and run it. With a QGIS project loaded, type the following into the editor:

for layer in iface.legendInterface().layers():
    print layer.name() 

As you can probably guess, this program prints out the names of the various layers within the current project. To run this program, save it by clicking on the Save As... toolbar icon; then, either click on the Run script toolbar icon (Using the console), or type the keyboard shortcut, Ctrl + Shift + E (that's command + Shift + E on Mac). You should see something like the following appear in the Interpreter Log:

>>> execfile(u'/.../tmp1NR24f.py'.encode('utf-8'))
water
urban
basemap

Note that QGIS uses the execfile() function (which is part of the Python standard library) to execute your script.

Tip

If your program didn't display the names of any layers, make sure you have a project loaded with at least one layer. In this example, we've used the example project we created in the previous chapter, which had three layers in it.

Of course, there is a lot more that we can do with the QGIS Console and its built-in Python editor, and we'll be using it to do useful work shortly. Before we do, though, there are two final things you should know about the QGIS Console.

Firstly, the console itself is written in Python using PyQt and the PyQScintilla2 editor. You can learn a lot about how QGIS has been implemented by looking through the source code to the console, which is available at https://github.com/qgis/QGIS/tree/master/python/console.

The second thing you should know is that the console is implemented as a Qt "Dockable" window; that is, it can be dragged into a pane within the main QGIS window. If you click and hold the console's title bar, you can drag it inside the main window, as shown in the following illustration:

Using the console

The console can be moved into any of the existing panes within the QGIS window, and it will stay there until you move it out.

To turn the console into a window again, click on the title bar and drag it out of the QGIS window. Alternatively, you can double-click on the console's title bar to switch between having it as a standalone window or a docked pane.

This docking behavior can be annoying if you're working on a small screen, where you can accidentally dock the console window while moving it out of the way so you can see what is beneath it. Fortunately, since the QGIS Console is implemented in PyQt, you can disable this quite easily by running the following Python code:

from console import console
from PyQt4.QtCore import Qt
console._console.setAllowedAreas(Qt.DockWidgetAreas(Qt.NoDockWidgetArea))

If you want, you can create a startup script that automatically shows the console and makes it nondockable whenever QGIS starts up. The startup script is stored in a hidden directory in your user or home folder. Using your file manager, look for a hidden directory named .qgis2 (or .qgis, depending on which version of QGIS you are running) in your user or home directory (for Mac OS X, you can use the Go to Folder... item in the Finder's Go menu). Inside this directory, there will be a subdirectory named python. Inside the python directory, create a file named startup.py and place the following into this file:

from console import console
from PyQt4.QtCore import Qt
console.show_console()
console._console.setAllowedAreas(Qt.DockWidgetAreas(Qt.NoDockWidgetArea))

As you can see, the only thing we changed was to add a call to console.show_console() to open the console window when QGIS starts.

Note

If the console is currently docked, this script won't undock it, although it will prevent you from accidentally docking the console again.