From 794ef725202825fa71d80d4733d5f554c4f8c4a9 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 7 Apr 2016 12:02:50 +0200 Subject: [PATCH] [processing] added support for QGIS variables in python scripts --- .../processing/script/ScriptAlgorithm.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/script/ScriptAlgorithm.py b/python/plugins/processing/script/ScriptAlgorithm.py index 8b5eee79caca..9531c79d4ea4 100644 --- a/python/plugins/processing/script/ScriptAlgorithm.py +++ b/python/plugins/processing/script/ScriptAlgorithm.py @@ -26,6 +26,8 @@ __revision__ = '$Format:%H$' import os +import re +from qgis.core import * from PyQt.QtGui import QIcon from processing.core.GeoAlgorithm import GeoAlgorithm from processing.gui.Help2Html import getHtmlFromHelpFile @@ -53,6 +55,7 @@ from processing.core.outputs import OutputDirectory from processing.core.outputs import getOutputFromString from processing.script.WrongScriptException import WrongScriptException +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException pluginPath = os.path.split(os.path.dirname(__file__))[0] @@ -307,9 +310,6 @@ def processDescriptionParameterLine(self, line): 'Problem with line %d', 'ScriptAlgorithm') % (self.descriptionFile or '', line)) def processAlgorithm(self, progress): - - script = 'import processing\n' - ns = {} ns['progress'] = progress ns['scriptDescriptionFile'] = self.descriptionFile @@ -320,7 +320,18 @@ def processAlgorithm(self, progress): for out in self.outputs: ns[out.name] = out.value + variables = re.findall("@[a-zA-Z0-9_]*", self.script) + print variables + script = 'import processing\n' script += self.script + + scope = QgsExpressionContextUtils.projectScope() + for var in variables: + varname = var[1:] + if not scope.hasVariable(varname): + raise GeoAlgorithmExecutionException("Wrong variable: %s" % varname) + script = script.replace(var, scope.variable(varname)) + exec((script), ns) for out in self.outputs: out.setValue(ns[out.name])