Important

La traduction est le fruit d’un effort communautaire auquel vous pouvez vous joindre. Cette page est actuellement traduite à 31.30%.

25.3. La Console Python de QGIS

Comme vous le verrez plus loin dans ce chapitre, QGIS a été conçu avec une architecture de plugin. Les plugins peuvent être écrits en Python, un langage très célèbre dans le monde géospatial.

QGIS apporte une API Python (voir le Livre de recettes PyQGIS pour obtenir un exemple de code) pour permettre à l’utilisateur d’interagir avec ses objets (couches, entités ou interface). QGIS possède également une console Python.

The QGIS Python Console is an interactive shell for Python command executions. It also has a Python file editor that allows you to edit and save your Python scripts. Both console and editor are based on PyQScintilla2 package. To open the console go to Plugins ► Python Console (Ctrl+Alt+P) or click on the pythonFile Python Console icon in the Plugins toolbar.

25.3.1. La console interactive

The console is a Python interpreter that allows you to execute Python commands. Modules from QGIS (analysis, core, gui, server, processing, 3d) and Qt (QtCore, QtGui, QtNetwork, QtWidgets, QtXml) as well as Python’s math, os, re and sys modules are already imported and can be used directly.

La console interactive est composée d’une barre d’outils, d’une zone d’entrée et de sortie.

../../../_images/python_console.png

Fig. 25.17 La console Python

25.3.1.1. Barre d’outils

La barre d’outil propose les outils suivant:

25.3.1.2. Input area

The Console input area main features are:

  • Auto-complétion du code, coloration et rappels syntaxiques pour les APIs suivantes :

    • Python

    • PyQGIS

    • PyQt5

    • QScintilla2

    • osgeo-gdal-ogr

    • osgeo-geos

  • Ctrl+Alt+Space pour voir la liste d’auto-complétion si elle est activée dans Python settings ;

  • Exécutez des fragments de code depuis la zone de saisie en les tapant puis en appuyant sur Entrée ou Exécuter la Commande ;

  • Exécutez des extraits de code à partir de la zone de sortie en utilisant Entrez la sélection dans le menu contextuel ou en appuyant sur Ctrl+E ;

  • Parcourez l’historique des commandes dans la zone de saisie en utilisant les touches directionnelles Haut et Bas et exécutez la commande que vous voulez ;

  • Ctrl+Shift+Espace pour voir l’historique des commandes: un double clic sur une ligne exécutera la commande. La boîte de dialogue Historique des Commandes peut aussi être ouverte depuis le menu contextuel ou la zone de saisie ;

  • Sauvegarder et vider l’historique des commandes. L’historique sera sauvegardé dans le fichier console_history.txt du profil utilisateur en cours;

  • Type the following special commands:

    • ? to show a help of the Python Console

    • _api to open QGIS C++ API documentation or _api(object) for a specific object documentation (in QGIS C++ API or Qt API documentation)

    • _pyqgis to open QGIS Python API documentation or _pyqgis(object) for a specific object documentation (in QGIS Python API or Qt API documentation)

    • _cookbook to open PyQGIS Cookbook.

    • ! followed by a command to execute Shell commands from the Python Console. The console will start a subprocess, and forward its output to the Python Console Output. While the subprocess is running, the Python Console Input switches to STDIN mode and forwards entered character to the child process. This makes it possible to send confirmation when the child program asks for it. When the Console is in STDIN mode, pressing Ctrl+C kills the subprocess. It is also possible to affect the result of a command to a variable with the syntax var = !cmd

      >>> !echo QGIS Rocks!
      QGIS Rocks
      
      >>> !gdalinfo --version
      GDAL 3.10.3, released 2025/04/01
      
      >>> !pip install black
      # Install black python formatter using pip (if available)
      
      >>> sql_formats = !ogrinfo --formats | grep SQL
      >>> sql_formats
      ['SQLite -vector- (rw+v): SQLite / Spatialite', '  MSSQLSpatial -vector- (rw+): Microsoft SQL Server Spatial Database', '  PostgreSQL -vector- (rw+): PostgreSQL/PostGIS', '  MySQL -vector- (rw+): MySQL', '  PGDUMP -vector- (w+v): PostgreSQL SQL dump']
      

Astuce

Réutilisez des commandes déjà exécutées depuis la zone de sortie

Vous pouvez exécuter des fragments de code depuis la zone de sortie en les sélectionnant et en appuyant sur Ctrl+E. Peu importe que le texte sélectionné contienne les caractères d’attente de l’interpréteur (>>>,``…``).

25.3.2. L’éditeur de code

Use the showEditorConsole Show Editor button in the Interactive Console to enable the editor widget. It allows editing and saving Python scripts and offers advanced functionalities to manage your code. Depending on the enabled settings, it provides various capabilities for easier code writing, such as code completion, highlighting syntax and calltips for supported APIs. Automatic indentation, parenthesis insertion, code commenting and syntax checking are also available.

../../../_images/python_console_editor.png

Fig. 25.18 L’éditeur de console Python

The code editor area allows to simultaneously work on different scripts, each in a specific tab. Press symbologyAdd New editor to add a new tab. You can run partially or totally a script from the Code Editor and output the result in the Interactive Console output area.

Astuce

Press Ctrl+Space to view the auto-completion list.

At the top of the dialog, a toolbar provides access to a few commands. Right-clicking the editor area provides some more options. All available tools are described in the following table.

Tableau 25.1 Python Console Editor Tools

Tool name

Function

Location

scriptOpen Open script…

Loads a Python file in the code editor dialog, as a new tab

Barre d’outils

showEditorConsole Open in external editor…

Opens a saved Python script in the default external program set for Python file editing

fileSave Save (Ctrl+S)

Saves the current script

fileSaveAs Save as… (Ctrl+Shift+S)

Saves the current script as a new file

start Run script (Ctrl+Shift+E)

Executes the whole script in the Interactive console (this creates a byte-compiled file with the extension .pyc)

Toolbar & Contextual menu

helpContents Context help (F1)

Attempts to display help on the selected string (class, method, object,…) in its corresponding API documentation

Contextual menu

runConsole Run selected (Ctrl+E)

Executes in the Interactive console the lines selected in the script

Toolbar & Contextual menu

editCut Cut (Ctrl+X)

Cuts selected text to the clipboard

editCopy Copy (Ctrl+C)

Copies selected text to the clipboard

editPaste Paste (Ctrl+V)

Pastes a cut or copied text

searchEditorConsole Find text

Allows to search and replace a text in the script.

  • Utilisez le raccourci par défaut de l’environnement de bureau pour trouver le suivant / précédent (Ctrl+G et Shift+Ctrl+G) ;

  • Rechercher automatiquement la première correspondance lors de la saisie dans la zone de recherche ;

  • Définissez la chaîne de recherche initiale sur sélection lors de l’ouverture de la recherche ;

  • Enable the searchRegex Use Regular Expressions option in the search bar to use regular expressions instead of plain text matching;

  • replace Replace the matching text with the text in the replace box. When using a regular expression, you can reference captured groups (e.g. via \1) in the replacement text. Use Replace All to replace all matches at once.

  • Appuyer sur Esc ferme la barre de recherche.

commentEditorConsole Toggle comment (Ctrl+:)

Comments out or uncomment selected lines, by adding or removing # character (potentially followed by a space) at the start of the lines. If the selection contains both comments and actual commands, adds # at the start of each non empty line. Pressing again the button reverts to the initial state.

formatCode Reformat code (Ctrl+Alt+F)

Allows to manually apply various formatting rules (sort imports, indentation, line length,…) to the code, following user-defined settings. This may require installation of additional Python modules.

classBrowserConsole Object inspector…

Shows and hides a dedicated browser with a tree structure for classes and functions available in the script. Click an item fo a quick access to its definition. The tool requires an activation from the Python settings - Run and Debug.

Hide editor

Hides the Python code editor block. To make it visible again, press showEditorConsole Show editor button from the interactive console toolbar.

Contextual menu

syntaxErrorConsole Check syntax (Ctrl+4)

Browses the code and reports syntax errors, such as missing parenthesis, colons, wrong indentation,…

undo Undo (Ctrl+Z)

Undoes the latest action

redo Redo (Ctrl+Shift+Z)

Reverts undone actions to a more recent

Select all (Ctrl+A)

Selects the whole script

codepadConsole Share on GitHub

Shares the script as a Secret Gist or Public Gist on GitHub, provided a GitHub access token.

options Options…

Opens the Python settings dialog.