Importante

La traducción es un esfuerzo comunitario puede unirse. Esta página está actualmente traducida en |progreso de traducción|.

25.3. Consola Python de QGIS

Como verá más adelante en este capítulo, QGIS ha sido diseñado con una arquitectura de complementos. Los complementos se pueden escribir en Python, un lenguaje muy famoso en el mundo geoespacial.

QGIS trae una API de Python (ver PyQGIS Developer Cookbook para algunos ejemplos de código) para permitir que el usuario interactúe con sus objetos (capas, función o interfaz). QGIS también tiene una consola 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 consola interactiva

La consola es un intérprete de Python que permite ejecutar comandos de Python. Los módulos de QGIS (analysis, core, gui, server, processing, 3d) y Qt (QtCore, QtGui, QtNetwork, QtWidgets, QtXml) así como los módulos math, os, re y sys de Python ya están importados y se pueden utilizar directamente.

La consola interactiva esta compuesta por una barra de herramientas, un área de entrada y una de salida.

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

Figura 25.17 Consola de Python

25.3.1.1. Barra de herramietas

La barra de herramientas propone las siguientes herramientas:

25.3.1.2. Área de entrada

Las principales prestaciones del área de introducción de datos de la consola son:

  • Completado de código, resaltado de sintaxis y atajos para las siguientes APIs:

    • Python

    • PyQGIS

    • PyQt5

    • QScintilla2

    • osgeo-gdal-ogr

    • osgeo-geos

  • Ctrl+Alt+Espacio para ver la lista de autocompletado habilitados en Configuración de Python;

  • Ejecute fragmentos de código desde el área de entrada escribiendo y presionando Enter o Ejecutar comando;

  • Ejecute fragmentos de código desde el área de salida usando :guilabel:ʻIntroducir seleccionado` del menú contextual o presionando Ctrl+E;

  • Examine el historial de comandos desde el área de entrada usando las teclas de flecha Arriba y Abajo y ejecute el comando que desee;

  • Ctrl+Shift+Espacio para ver el historial de comandos: haga doble clic en una fila para ejecutar el comando. También se puede acceder al diálogo Historial de comandos desde el menú contextual del área de entrada;

  • Guarde y borre el historial de comandos. El historial se guardará en el archivo console_history.txt en la carpeta activa user profile;

  • Escriba los siguientes comandos especiales:

    • ? para mostrar una ayuda de la Consola Python

    • _api para abrir la documentación QGIS C++ API o _api(object) para la documentación de un objeto específico (en la documentación de QGIS C++ API o Qt API)

    • _pyqgis para abrir la documentación de API Python QGIS o _pyqgis(object) para la documentación de un objeto específico (en la documentación de la API Python QGIS o la API Qt).

    • _cookbook para abrir PyQGIS Cookbook.

    • ! seguido de un comando para ejecutar comandos Shell desde la Consola de Python. La consola iniciará un subproceso, y reenviará su salida a la Salida de la Consola Python. Mientras se ejecuta el subproceso, la Entrada de la Consola Python cambia al modo STDIN y reenvía los caracteres introducidos al proceso hijo. Esto hace posible enviar confirmación cuando el programa hijo la pide. Cuando la Consola está en modo STDIN, pulsando Ctrl+C se mata el subproceso. También es posible afectar el resultado de un comando a una variable con la sintaxis 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']
      

Truco

Reutilizar comandos ejecutados desde el panel de salida

Puede ejecutar fragmentos de código desde el panel de salida seleccionando un texto y presionando Ctrl+E. No importa si el texto seleccionado contiene la indicación del intérprete (>>>, ...).

25.3.2. El Editor de código

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

Figura 25.18 El editor de la consola de 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.

Truco

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.

Tabla 25.1 Python Console Editor Tools

Tool name

Function

Localización

scriptOpen Open script…

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

Barra de herramietas

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.

  • Utilice el acceso directo del entorno de escritorio predeterminado para buscar el siguiente/anterior (Ctrl+G y Shift+Ctrl+G);

  • Automáticamente encuentra la primera coincidencia al escribir en el cuadro de búsqueda;

  • Establecer la cadena de búsqueda inicial a la selección al abrir la búsqueda;

  • Habilite la opción searchRegex Usar expresiones regulares en la barra de búsqueda para utilizar expresiones regulares en lugar de la coincidencia de texto sin formato;

  • 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.

  • Presionando Esc cierra la barra de búsqueda.

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 for 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 Configuración de Python dialog.