>>> from env_helper import info; info()
页面更新时间: 2024-07-23 23:38:19
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-23-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

12.1. 在 QGIS 中使用 Python

QGIS 中有 Python 的运行环境,可以很好地执行各种任务。 这里的问题是如何在 Jupyter 中调用 QGIS 的功能。

首先可以肯定的是涉及到 GUI 的一些任务是无法在 Jupyter 中访问的, 这样可以用的功能主要是地处理工具。

按如下方式进行了尝试。 原想使用 gdal:hillshade ,但是始终无法成功(这个运行失败需要重启内核)。 后来参考 https://cloud.tencent.com/developer/article/1971960 , 成功运行了另一个工具 native:creategrid 。 这样问题就变成哪些处理工具可用,哪些不可用。

另外要注意运行时使用的函数与参数与本地运行要求不完全一样。

>>> import sys
>>> sys.path
['/home/bk/book-jubook/python/jubook_python/pt40_pygis/ch12_qgis',
 '/usr/lib/python311.zip',
 '/usr/lib/python3.11',
 '/usr/lib/python3.11/lib-dynload',
 '',
 '/usr/local/lib/python3.11/dist-packages',
 '/usr/lib/python3/dist-packages',
 '/usr/lib/python3.11/dist-packages',
 '/usr/share/qgis/python/plugins',
 '/usr/share/qgis/python/plugins']
>>> from qgis.core import *
>>> sys.path.append('/usr/share/qgis/python/plugins')
>>> import processing
>>> from processing.core.Processing import Processing
>>> from processing.core.Processing import QgsProcessingFeedback
>>> Processing.initialize()
>>> from qgis.analysis import QgsNativeAlgorithms
>>> QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
Logged warning: Duplicate provider native registered
False

查看渔网创建工具的说明文档:

>>> # QgsApplication.processingRegistry().algorithms()
>>>
>>> from processing import algorithmHelp
>>>
>>>
>>> algorithmHelp("native:creategrid")
Create grid (native:creategrid)

This algorithm creates a vector layer with a grid covering a given extent. Elements in the grid can be points, lines or polygons. The size and/or placement of each element in the grid is defined using a horizontal and vertical spacing. The CRS of the output layer must be defined. The grid extent and the spacing values must be expressed in the coordinates and units of this CRS. The top-left point (minX, maxY) is used as the reference point. That means that, at that point, an element is guaranteed to be placed. Unless the width and height of the selected extent is a multiple of the selected spacing, that is not true for the other points that define that extent.


----------------
Input parameters
----------------

TYPE: Grid type

    Parameter type: QgsProcessingParameterEnum

    Available values:
            - 0: Point
            - 1: Line
            - 2: Rectangle (Polygon)
            - 3: Diamond (Polygon)
            - 4: Hexagon (Polygon)

    Accepted data types:
            - int
            - str: as string representation of int, e.g. '1'
            - QgsProperty

EXTENT: Grid extent

    Parameter type: QgsProcessingParameterExtent

    Accepted data types:
            - str: as comma delimited list of x min, x max, y min, y max. E.g. '4,10,101,105'
            - str: layer ID. Extent of layer is used.
            - str: layer name. Extent of layer is used.
            - str: layer source. Extent of layer is used.
            - QgsMapLayer: Extent of layer is used
            - QgsProcessingFeatureSourceDefinition: Extent of source is used
            - QgsProperty
            - QgsRectangle
            - QgsReferencedRectangle
            - QgsGeometry: bounding box of geometry is used

HSPACING: Horizontal spacing

    Parameter type: QgsProcessingParameterDistance

    Accepted data types:
            - int
            - float
            - QgsProperty

VSPACING: Vertical spacing

    Parameter type: QgsProcessingParameterDistance

    Accepted data types:
            - int
            - float
            - QgsProperty

HOVERLAY: Horizontal overlay

    Parameter type: QgsProcessingParameterDistance

    Accepted data types:
            - int
            - float
            - QgsProperty

VOVERLAY: Vertical overlay

    Parameter type: QgsProcessingParameterDistance

    Accepted data types:
            - int
            - float
            - QgsProperty

CRS: Grid CRS

    Parameter type: QgsProcessingParameterCrs

    Accepted data types:
            - str: 'ProjectCrs'
            - str: CRS auth ID (e.g. 'EPSG:3111')
            - str: CRS PROJ4 (e.g. 'PROJ4:…')
            - str: CRS WKT (e.g. 'WKT:…')
            - str: layer ID. CRS of layer is used.
            - str: layer name. CRS of layer is used.
            - str: layer source. CRS of layer is used.
            - QgsCoordinateReferenceSystem
            - QgsMapLayer: CRS of layer is used
            - QgsProcessingFeatureSourceDefinition: CRS of source is used
            - QgsProperty

OUTPUT: Grid

    Parameter type: QgsProcessingParameterFeatureSink

    Accepted data types:
            - str: destination vector file, e.g. 'd:/test.shp'
            - str: 'memory:' to store result in temporary memory layer
            - str: using vector provider ID prefix and destination URI, e.g. 'postgres:…' to store result in PostGIS table
            - QgsProcessingOutputLayerDefinition
            - QgsProperty

----------------
Outputs
----------------

OUTPUT:  <QgsProcessingOutputVectorLayer>
    Grid
>>> assert len(QgsApplication.processingRegistry().algorithms()) > 0
>>> rasterLyr = QgsRasterLayer("/gdata/dem_data.tif", "reproject")
>>> # rasterLyr = "/gdata/dem_data.tif"
Application path not initialized
Application path not initialized
>>> # assert rasterLyr.isValid()
>>> parameters = {'INPUT': rasterLyr,
>>>                 'BAND': 1,
>>>                 'COMPUTE_EDGES': False,
>>>                 'ZEVENBERGEN': False,
>>>                 'Z_FACTOR': 1.0,
>>>                 'SCALE': 1.0,
>>>                 'AZIMUTH': 315,
>>>                 'COMBINED': False,
>>>                 'ALTITUDE': 45,
>>>                 'MULTIDIRECTIONAL': False,
>>>                 'OUTPUT': "/tmp/hillshade.tif"}
>>> # processing.run('gdal:hillshade',parameters,  feedback=feedback)
>>> params = {'TYPE':0,'EXTENT':'-3.500000000,3.500000000,-1.000000000,1.000000000 [EPSG:4326]','HSPACING':1,'VSPACING':1,'HOVERLAY':0,'VOVERLAY':0,'CRS':QgsCoordinateReferenceSystem('EPSG:4326'),'OUTPUT':'xx_aa.shp'}
>>> # processing.run("native:creategrid", para ,
>>>               # )
>>>
>>> feedback = QgsProcessingFeedback()
>>> processing.run("native:creategrid", params, feedback=feedback)
{'OUTPUT': 'xx_aa.shp'}