Importante

A tradução é um esforço comunitário você pode contribuir. Esta página está atualmente traduzida em 52.05%.

29.3. Terminal Python QGIS

Como você verá mais adiante neste capítulo, o QGIS foi projetado com uma arquitetura de plugin. Plugins podem ser escritos em Python, uma linguagem muito famosa no mundo geoespacial.

QGIS brings a Python API (see PyQGIS Developer Cookbook for some code sample) to let the user interact with its objects (layers, feature or interface). QGIS also has a Python console.

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

29.3.1. O console interativo

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.

The interactive console is composed of a toolbar, an input area and an output one.

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

Fig. 29.15 O Console Python

29.3.1.1. Barra de Ferramentas

The toolbar proposes the following tools:

29.3.1.2. Input area

The Console input area main features are:

  • Code completion, highlighting syntax and calltips for the following APIs:

    • Python

    • PyQGIS

    • PyQt5

    • QScintilla2

    • osgeo-gdal-ogr

  • Ctrl+Alt+Space para visualizar a lista de auto-preenchimento se habilitado no :ref:`console_options’;

  • Execute trechos de código da área de entrada digitando e pressionando Enter ou Executar Comando;

  • Execute code snippets from the output area using the Enter Selected from the contextual menu or pressing Ctrl+E;

  • Navegue pelo histórico de comandos da área de entrada utilizando as teclas de seta Cima e Baixo e execute o comando desejado;

  • Ctrl+Shift+Space' para visualizar o histórico de comandos: clicando duas vezes em uma linha, o comando será executado. O diálogo :guilabel:`Histórico de Comando também pode ser acessado a partir do menu de contexto da área de entrada;

  • Save and clear the command history. The history will be saved into the console_history.txt file under the active user profile folder;

  • 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.6.2, released 2023/01/02
      
      >>> !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']
      

Dica

Reutilize comandos executados do painel de saída

You can execute code snippets from the output panel by selecting some text and pressing Ctrl+E. No matter if selected text contains the interpreter prompt (>>>, ...).

29.3.2. O Editor de Código

Use the showEditorConsole Show Editor button to enable the editor widget. It allows editing and saving Python files and offers advanced functionalities to manage your code (comment and uncomment code, check syntax, share the code via GitHub and much more). Main features are:

  • Code completion, highlighting syntax and calltips for the following APIs:

    • Python

    • PyQGIS

    • PyQt5

    • QScintilla2

    • osgeo-gdal-ogr

  • :kbd:`Ctrl+Space’ para visualizar a lista de auto-preenchimento.

  • Compartilhamento de trechos de código através de GitHub.

  • Ctrl+4 Verificação de sintaxe.

  • Barra de busca (abra-a com o atalho padrão do ambiente Desktop, geralmente Ctrl+F):

    • Use the default Desktop Environment shortcut to find next/previous (Ctrl+G and Shift+Ctrl+G);

    • Encontrar automaticamente a primeira correspondência ao digitar na caixa de busca;

    • Defina a string de busca inicial para a seleção ao abrir a busca;

    • Pressionando Esc fecha a barra de busca.

  • Object inspector: a class and function browser;

  • Go to an object definition with a mouse click (from Object inspector);

  • Execute code snippets with the runConsole Run Selected command in contextual menu;

  • Execute the whole script with the start Run Script command (this creates a byte-compiled file with the extension .pyc).

Nota

Running partially or totally a script from the Code Editor outputs the result in the Console output area.

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

Fig. 29.16 O editor do console Python

Dica

Salvar as opções

To save the state of console’s widgets you have to close the Python Console from the close button. This allows you to save the geometry to be restored to the next start.