Thursday, 28 June 2018

qgis 2 - How to terminate Python scripts in Processing framework properly?


I'm writing a Python script to use it in Processing framework. I need to cancel script execution if certain conditions are met (to save user's time). I tried to use sys.exit(arguments) command. The issue is that not only the script, but QGIS itself shuts down too. I also tried quit() but result is the same. How should I terminate script in Processing framework?


UPDATE: Note, that following code is for reproduction purpose only. I don't need ad hoc solution for this particular case because I already have it. I need to know how to deal with this issue in general.


##Raster processing=group
##raster_1=raster
##raster_2=raster



from osgeo import gdal
import sys
from numpy import *
import ntpath
import re
import platform
from PyQt4 import QtGui



raster_1 = gdal.Open(raster_1)
raster_2 = gdal.Open(raster_2)

rasters_list = [raster_1, raster_2]

# create a message for the case when CRSs of rasters do not match
class WrongCRS(QtGui.QMessageBox):

def __init__(self):

super(WrongCRS, self).__init__()

self.initUI()

def initUI(self):

self.warning(self, 'Oops!',
"Rasters must have the same CRS!\n\nExecution cancelled!", QtGui.QMessageBox.Ok)

# check CRS

proj = None
for raster in rasters_list:
new_proj = raster.GetProjection()
if proj is None:
proj = new_proj
else:
if proj != new_proj:
WrongCRS()
sys.exit('CRSs do not match!')
else:

continue

Answer



It is impossible (for now at least) to terminate Processing python script and leave QGIS itself untouched. It was suggested by @gene to use sys.exitfunc() to terminate main function. However I find it more useful to use just return message to just end function normally. Here is pseudo code:


class ErrorMessage(...):
.....

def checkFunction(parameter):
if parameter == condition:
return False
else:

return True

def jobFunction(...):
...
if parameter_1 == condition_1:
return False

result = ...
return result


def main(...):
if not checkFunction(parameter):
return ErrorMessage(...)

result = jobFunction(...)
if result == False:
return ErrorMessage(...)

return result


main(...)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...