Viktigt

Översättning är en gemenskapsinsats du kan gå med i. Den här sidan är för närvarande översatt till 51.91%.

25.3. QGIS Python-konsol

Som du kommer att se senare i detta kapitel har QGIS utformats med en tilläggsarkitektur. Tillägg kan skrivas i Python, ett mycket känt språk i den geospatiala världen.

QGIS har ett Python API (se PyQGIS Developer Cookbook för några kodexempel) för att låta användaren interagera med dess objekt (lager, funktion eller gränssnitt). QGIS har också en Python-konsol.

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. Den interaktiva konsolen

Konsolen är en Python-tolk som gör att du kan köra Python-kommandon. Moduler från QGIS (analysis, core, gui, server, processing, 3d) och Qt (QtCore, QtGui, QtNetwork, QtWidgets, QtXml) samt Pythons moduler math, os, re och sys är redan importerade och kan användas direkt.

Den interaktiva konsolen består av ett verktygsfält, en inmatningsyta och en utmatningsyta.

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

Fig. 25.17 Python-konsolen

25.3.1.1. Verktygsrad

I verktygsfältet finns följande verktyg:

  • clearConsole Clear Console för att rensa utmatningsområdet;

  • start Kör kommando tillgängligt i inmatningsområdet: samma sak som att trycka på Enter;

  • showEditorConsole Visa redigerare: växlar synlighet för Kodredigeraren;

  • options Alternativ…: öppnar en dialogruta för att konfigurera konsolegenskaper;

  • helpContents Hjälp… innehåller en meny för att komma åt olika dokument:

  • dock Dock Code Editor för att docka eller undocka panelen i QGIS-gränssnittet

25.3.1.2. Inmatningsområde

De viktigaste funktionerna i konsolens inmatningsområde är

  • Kodkomplettering, syntaxmarkering och anropstips för följande API:er:

    • Python

    • PyQGIS

    • PyQt5

    • QScintilla2

    • osgeo-gdal-ogr

    • osgeo-geos

  • Ctrl+Alt+Space för att visa listan för automatisk komplettering om den är aktiverad i Python-inställningar;

  • Kör kodsnuttar från inmatningsområdet genom att skriva och trycka på Enter eller Run Command;

  • Exekvera kodavsnitt från utmatningsområdet med hjälp av Enter Selected från snabbmenyn eller genom att trycka på Ctrl+E;

  • Bläddra igenom kommandohistoriken från inmatningsområdet med hjälp av piltangenterna Upp och Ned och kör det kommando du vill ha;

  • Ctrl+Shift+Space för att visa kommandohistoriken: dubbelklicka på en rad för att utföra kommandot. Dialogrutan Kommandohistorik kan också nås från kontextmenyn i inmatningsområdet;

  • Spara och rensa kommandohistoriken. Historiken sparas i filen console_history.txt under den aktiva mappen användarprofil;

  • Skriv in följande specialkommandon:

    • ? för att visa en hjälp av Python-konsolen

    • _api för att öppna QGIS C++ API dokumentation eller _api(object) för en specifik objektdokumentation (i QGIS C++ API eller Qt API dokumentation)

    • _pyqgis för att öppna QGIS Python API dokumentation eller _pyqgis(object) för en specifik objektdokumentation (i QGIS Python API eller Qt API dokumentation)

    • _cookbook to open PyQGIS Cookbook.

    • ! följt av ett kommando för att köra Shell-kommandon från Python-konsolen. Konsolen startar en underprocess och vidarebefordrar dess utdata till Python Console Output. Medan subprocessen körs växlar Python Console Input till STDIN-läge och vidarebefordrar inmatade tecken till barnprocessen. Detta gör det möjligt att skicka en bekräftelse när barnprogrammet ber om det. När konsolen är i STDIN-läge kan man trycka på Ctrl+C för att döda underprocessen. Det är också möjligt att påverka resultatet av ett kommando till en variabel med syntaxen 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']
      

Tips

Återanvända utförda kommandon från utmatningspanelen

Du kan köra kodsnuttar från utdatapanelen genom att markera text och trycka på Ctrl+E. Det spelar ingen roll om den markerade texten innehåller tolkens prompt (>>>, ...).

25.3.2. Kodredigeraren

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 Python Console-editorn

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.

Tips

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.

Table 25.1 Python Console Editor Tools

Tool name

Function

Plats

scriptOpen Open script…

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

Verktygsrad

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.

  • Använd standardgenvägen i skrivbordsmiljön för att hitta nästa/förra (Ctrl+G och Shift+Ctrl+G);

  • Hitta automatiskt den första matchningen när du skriver i sökrutan;

  • Ställ in initial söksträng till val när du öppnar sökningen;

  • Aktivera alternativet searchRegex Använd reguljära uttryck i sökfältet för att använda reguljära uttryck istället för vanlig textmatchning.

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

  • Tryck på Esc för att stänga sökfältet.

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 Python-inställningar dialog.