QGIS python scripts

Hello,

I want to run a python script the uses the python package that ships internally with QGIS.

The script I wish to run includes

from qgis.core import (
    QgsApplication,
    QgsLayoutExporter,
    QgsVectorLayer,
    QgsVectorLayerJoinInfo,
    QgsProject,
    QgsProperty,
    QgsRuleBasedRenderer,
    QgsUnitTypes,
    QgsSymbol,
    QgsSymbolLayer
)
from qgis.PyQt.QtGui import QColor

In a very hacky fashion I have set up my environment like this:

nix-shell -p qgis 'qgis.override { extraPythonPackages = (ps: with ps; [ numpy future pandas gdal]);}' python39 'python39.withPackages(ps: with ps; [ ipython pandas gdal pyqt5])'
export PYTHONPATH=$PYTHONPATH:`which qgis`/../../share/qgis/python

And on running my script

python myscript.py ...

Get the following error:

2022-02-18 11:12:36,579 [INFO ] initialising QGIS
qt.qpa.plugin: Could not find the Qt platform plugin "xcb" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Aborted (core dumped)

Any thoughts and advice appreciated :slight_smile:

In case anyone is interested, the following derivation works for me in the nix-shell

# {pkgs ? import <nixpkgs> {} }:
{pkgs ? import (builtins.fetchTarball {
  name = "nixos-21.11";
  url = "https://github.com/NixOS/nixpkgs/archive/refs/tags/21.11.tar.gz";
  sha256 = "sha256:162dywda2dvfj1248afxc45kcrg83appjd0nmdb541hl7rnncf02";
}) {} }:
let
in
pkgs.mkShell rec {
  buildInputs = with pkgs; [
    xorg.libxcb
    qgis
    qt5.full
    qtcreator
    python38
    python38Packages.pyqt5
    python38Packages.gdal
    python38Packages.ipython
    python38Packages.pandas
    python38Packages.pytest
  ];
  shellHook = ''
  export PYTHONPATH=$PYTHONPATH:`which qgis`/../../share/qgis/python
  '';
}

With the proviso that if you are running headless the environment variable should be set:

export QT_QPA_PLATFORM=offscreen
1 Like