在独立的python脚本中导入QGIS处理?


10

我想编写一些使用Qgis处理工具箱的独立脚本。

我已经读了一些线程(例如,这里这里),但是找不到有效的解决方案。

在Ubuntu Xenial 16.04 LTS上使用Qgis 2.16.1

我的脚本的import部分如下所示:

# Python modules
import sys
import time
import os

# Qgis modules
from qgis.core import *
import qgis.utils
from PyQt4.QtCore import QFileInfo, QSettings

有人知道我无法导入处理模块吗?

通过简单的导入处理,我得到了:

Original exception was:
Traceback (most recent call last):
 File "/home/steph/Documents/Projets/20141227-CIM_Bishkek/Scripts/python/00-projets/20160811-AnalysesUAVs/20160811-UAVAnalyse.py", line 36, in <module>
import processing
 File "/usr/lib/python2.7/dist-packages/qgis/utils.py", line 607, in _import
mod = _builtin_import(name, globals, locals, fromlist, level)
ImportError: No module named processing

编辑(约瑟夫评论后)

我已经这样尝试过:

# Python modules
import sys
import time
import os

# Qgis modules
from qgis.core import *
import qgis.utils
from PyQt4.QtGui import *
app = QApplication([])
QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()
from PyQt4.QtCore import QFileInfo, QSettings
#from PyQt4.QtGui import *

# Prepare processing framework 
sys.path.append('/home/steph/.qgis2/python/plugins')
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *

但是行为却很奇怪:我的脚本一直运行到最后没有错误,但似乎“跳过”了应该执行的任务:-)换句话说,它一直运行到最后但没有执行任何操作。

我承认我的解释不是很清楚...我将进一步调查,但是如果有人有导入该模块的神奇解决方案(不是解决方法),请!

编辑2:添加我的整个脚本。抱歉,如果有点长。

# -*- coding: cp1252 -*-
########################################################
## Name: Performs various analyses on UAV imagery using Qgis
## Source Name: UAVanalyse.py
## Version: Python 2.7
## Author: Stephane Henriod
## Usage: Performs a set of analyses on UAV imagery
## Date 11.08.2016
## Modified: 
########################################################


# Import required modules

# Python modules
import sys
import time
import os

# Qgis modules
from qgis.core import *
import qgis.utils
from PyQt4.QtCore import QFileInfo, QSettings

# Custom modules
from config_work import *
import display_msg as disp
import clean_time as cl

def make_raster_layer(raster, log_file):
    """Creates a raster layer from the path to a raster, if the path exists and if the raster is valid

    Param_in:
        raster (string) -- The path to the raster to be transformed into a layer
        log_file (string) -- The path to the log file to write in

    Param_out:
        list: 
            [0] = full path to the raster 
            [1] = raster layer

    """

    if os.path.exists(raster):
        fileName = raster
        fileInfo = QFileInfo(fileName)
        baseName = fileInfo.baseName()
        rlayer = QgsRasterLayer(fileName, baseName)
        if rlayer.isValid():
            return [raster, rlayer]
    else:
        return False

def study_raster(rlayer, log_file):
    """Returns properties of a raster, if this one exists and is valid

    Param_in:
        rlayer (bin) -- A raster layer
        log_file (string) -- The path to the log file to write in

    """

    infos = {}

    if rlayer:
        infos['a - Width'] = rlayer.width()
        infos['b - Height'] = rlayer.height()
        infos['c - Extent'] = rlayer.extent().toString()
        infos['d - # bands'] = rlayer.bandCount()
        infos['e - X resolution'] = rlayer.rasterUnitsPerPixelX()
        infos['f - Y resolution'] = rlayer.rasterUnitsPerPixelY()
        return infos
    else:
        return False


def project_raster(raster, to_crs, log_file):
    """Projects a raster into another crs

    Param_in:
        raster (string) -- The path to the raster to be transformed into a layer
        to_crs (string) -- The coordinate reference system to which the layer must be projected
        log_file (string) -- The path to the log file to write in

    """

    img_out_name = os.path.splitext(os.path.basename(raster))[0] + '_proj' + os.path.splitext(os.path.basename(raster))[1]
    img_out = os.path.join(output_folder, img_out_name)
    #processing.runalg("gdalwarp -overwrite -s_srs EPSG:32642 -t_srs " + to_crs + " " + rlayer[0] + " " + img_out)

    msg = img_out    
    disp.display_msg(log_file, msg, 'a')

    return img_out_name

if __name__ == "__main__":
    t_start_script = time.localtime()
    t_start_script_clean = time.strftime("%Y%m%d-%H%M", t_start_script)

    # Checking the folders
    if not os.path.exists(input_folder_path):
        os.makedirs(input_folder_path)
    if not os.path.exists(temp_folder_path):
        os.makedirs(temp_folder_path)
    if not os.path.exists(output_folder_path):
        os.makedirs(output_folder_path)

    # Creating the output and temp folders
    output_folder = os.path.join(output_folder_path, t_start_script_clean + '-UAVanalyse')
    temp_folder = os.path.join(temp_folder_path, t_start_script_clean + '-UAVanalyse')

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    if not os.path.exists(temp_folder):
        os.makedirs(temp_folder)

    # Creating the log file
    log_file_name = t_start_script_clean + '-UAVanalyse.log'
    log_file = os.path.join(output_folder, log_file_name)

    # Heading of the log file
    msg = "Performs a set of analyses on UAV imagery" + os.linesep
    msg += "Input folder: " + input_folder_path
    msg += "\n RGB image: " + img_rgb_name
    msg += "\n NIR image: " + img_nir_name
    msg += "\n RGBIR image: " + img_rgbir_name
    msg += "\n DSM file: " + img_dsm_name
    disp.display_msg(log_file, msg, 'w')

    #msg = "Script started on " + cl.clean_time(t_start_script)
    #disp.display_msg(log_file, msg, 'a')


    # Initialize Qgis (source: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html)
    msg = 'Initialize Qgis'
    disp.display_msg(log_file, msg, 'a')
    # supply path to qgis install location
    QgsApplication.setPrefixPath("/usr", True)

    # create a reference to the QgsApplication, setting the
    # second argument to False disables the GUI
    qgs = QgsApplication([], False)

    # load providers
    qgs.initQgis()


    # Write your code here to load some layers, use processing algorithms, etc.

    # Make raster layers
    rlayer_rgb = make_raster_layer(img_rgb, log_file)
    rlayer_nir = make_raster_layer(img_nir, log_file)
    rlayer_rgbir = make_raster_layer(img_rgbir, log_file)
    rlayer_dsm = make_raster_layer(img_dsm, log_file)

    all_valid_layers = []
    if rlayer_rgb: all_valid_layers.append(rlayer_rgb)
    if rlayer_nir: all_valid_layers.append(rlayer_nir)
    if rlayer_rgbir: all_valid_layers.append(rlayer_rgbir)
    if rlayer_dsm: all_valid_layers.append(rlayer_dsm)




    # (I) Infos about the layers
    msg = os.linesep + frm_separator + os.linesep + '(I) Infos about the layers' + os.linesep + frm_separator + os.linesep
    disp.display_msg(log_file, msg, 'a')

    i = 1
    for layer in all_valid_layers:
        infos = study_raster(layer[1], log_file)
        msg = '\n (' + str(i) + ') ' + layer[0] + os.linesep
        for item in sorted(infos):
            msg += '\n ' + str(item) + ': ' + str(infos[item]) + os.linesep

        i+=1
        disp.display_msg(log_file, msg, 'a')

    msg = 'List of valid layers:' + os.linesep
    for layer in all_valid_layers:
        msg += layer[0]+ os.linesep
    disp.display_msg(log_file, msg, 'a')


    # (II) Projects the layers into the national coordinate system or any desired system
    msg = os.linesep + frm_separator + os.linesep + '(II) Projecting of the layers' + os.linesep + frm_separator + os.linesep
    disp.display_msg(log_file, msg, 'a')

    i = 1
    for layer in all_valid_layers:
        project_raster(layer[0], to_crs, log_file)




    # When script is complete, call exitQgis() to remove the provider and
    # layer registries from memory
    qgs.exitQgis()
    msg = 'Qgis has been closed'
    disp.display_msg(log_file, msg, 'a')

    #raw_input("Press Enter to continue...")

在第二个链接中,您是否使用了@GermánCarrillo提供的代码?他的代码也是我用来运行独立脚本的代码(使用Windows时,我会稍微修改路径)。
约瑟夫

您要执行的任务是什么?:)。您能否在问题中包含代码?这可以帮助其他人找出问题所在。
约瑟夫

我正在尝试编写一些函数来处理无人机图像。我需要做的第一件事是重新投影,这就是为什么我需要处理模块的原因。让我补充我的完整剧本,虽然我有点惭愧:我不是一个“真正”的开发人员,我敢肯定,我的代码是不是干净的或最直接的,你见过:-)
斯特凡Henriod

别羞愧!我发布的内容都不是最干净或直截了当的=)
约瑟夫

因此,我添加了整个脚本。随时查看:-)
斯特凡·亨里欧德

Answers:


6

Linux QGIS 2.18.1

有了此代码,就可以从独立脚本运行Processing:

#!/usr/bin/env python
import qgis
from qgis.core import *
import sys

app = QgsApplication([],True, None)
app.setPrefixPath("/usr", True)
app.initQgis()
sys.path.append('/usr/share/qgis/python/plugins')
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *

print Processing.getAlgorithm("qgis:creategrid")

这是唯一适用于我正在使用的环境的组合(在具有Python 2.7的Ubuntu 14.04计算机上的Pycharm C.Ed)。之前,我尝试了gis.stackexchange.com/questions/129513/…gis.stackexchange.com/questions/176821/…的组合,不幸的是,它们都没有导入“ processing.core.Processing”。我不知道为什么导入一个模块会令人困惑。记录:有一个纯Python软件包(也称为“处理”)遮盖了QGIS。
艾琳(Irene)

3

因此,我设法使其正常运行,感谢@Joseph的提示:

# Import required modules

# Python modules
import sys
import time
import datetime
import os
from getpass import getuser

# Qgis modules and environment
from qgis.core import *
import qgis.utils
from PyQt4.QtCore import QFileInfo, QSettings

from PyQt4.QtGui import QApplication
app = QApplication([])

QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()

# Prepare processing framework
sys.path.append('/home/' + getuser() + '/.qgis2/python/plugins')
from processing.core.Processing import Processing

Processing.initialize()

我很高兴与

print Processing.getAlgorithm("qgis:creategrid")

我想,我的问题来自以下事实:我在脚本的开头导入了模块,然后尝试从函数内部创建Qgi对象。我想也可以这样做,但是我的Python技能可能存在缺陷。

现在,我将尝试实际处理模块:-)


事情变了吗?我尝试使用此代码(来自Joseph)来将处理过程应用到独立脚本中,并且得到:ImportError:没有名为processing.core.Processing的模块,使用linux QGIS 2.18.1
Juanma Font
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.