Skip to content

Commit

Permalink
Merge pull request #4293 from alexbruy/processing-api
Browse files Browse the repository at this point in the history
[processing][needs-docs] Processing API improvements
  • Loading branch information
alexbruy committed Mar 27, 2017
2 parents 1f927ab + 1a46ddb commit b8cb196
Show file tree
Hide file tree
Showing 18 changed files with 81 additions and 58 deletions.
4 changes: 2 additions & 2 deletions python/plugins/processing/algs/grass7/Grass7Utils.py
Expand Up @@ -384,8 +384,8 @@ def checkGrass7IsInstalled(ignorePreviousState=False):
if Grass7Utils.isGrass7Installed:
return
try:
from processing import runalg
result = runalg(
from processing import run
result = run(
'grass7:v.voronoi',
points(),
False,
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/processing/algs/qgis/ConcaveHull.py
Expand Up @@ -68,7 +68,7 @@ def processAlgorithm(self, feedback):

# Delaunay triangulation from input point layer
feedback.setProgressText(self.tr('Creating Delaunay triangles...'))
delone_triangles = processing.runalg("qgis:delaunaytriangulation", layer, None)['OUTPUT']
delone_triangles = processing.run("qgis:delaunaytriangulation", layer, None)['OUTPUT']
delaunay_layer = processing.getObject(delone_triangles)

# Get max edge length from Delaunay triangles
Expand Down Expand Up @@ -107,8 +107,8 @@ def processAlgorithm(self, feedback):

# Dissolve all Delaunay triangles
feedback.setProgressText(self.tr('Dissolving Delaunay triangles...'))
dissolved = processing.runalg("qgis:dissolve", delaunay_layer,
True, None, None)['OUTPUT']
dissolved = processing.run("qgis:dissolve", delaunay_layer,
True, None, None)['OUTPUT']
dissolved_layer = processing.getObject(dissolved)

# Save result
Expand Down
Expand Up @@ -40,7 +40,7 @@

from processing.core.ProcessingConfig import ProcessingConfig
from processing.core.ProcessingLog import ProcessingLog
from processing.gui.AlgorithmExecutor import runalg
from processing.gui.AlgorithmExecutor import execute
from processing.tools import dataobjects
from processing.gui.Postprocessing import handleAlgorithmResults

Expand Down Expand Up @@ -232,7 +232,7 @@ def accept(self):
ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM,
self.alg.getAsCommand())

self.executed = runalg(self.alg, self.feedback)
self.executed = execute(self.alg, self.feedback)
if self.executed:
handleAlgorithmResults(self.alg,
self.feedback,
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/core/GeoAlgorithm.py
Expand Up @@ -524,7 +524,7 @@ def getAsCommand(self):
console.
"""

s = 'processing.runalg("' + self.commandLineName() + '",'
s = 'processing.run("' + self.commandLineName() + '",'
for param in self.parameters:
s += param.getValueAsCommandLineParameter() + ','
for out in self.outputs:
Expand Down
10 changes: 3 additions & 7 deletions python/plugins/processing/core/Processing.py
Expand Up @@ -49,7 +49,7 @@
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.RenderingStyles import RenderingStyles
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.gui.AlgorithmExecutor import runalg
from processing.gui.AlgorithmExecutor import execute
from processing.tools import dataobjects
from processing.core.alglist import algList

Expand Down Expand Up @@ -194,10 +194,6 @@ def getObject(uri):
"""Returns the QGIS object identified by the given URI."""
return dataobjects.getObjectFromUri(uri)

@staticmethod
def runandload(name, *args):
Processing.runAlgorithm(name, handleAlgorithmResults, *args)

@staticmethod
def runAlgorithm(algOrName, onFinish, *args, **kwargs):
if isinstance(algOrName, GeoAlgorithm):
Expand Down Expand Up @@ -251,7 +247,7 @@ def runAlgorithm(algOrName, onFinish, *args, **kwargs):
# fix_print_with_import
print('Error: Wrong number of parameters')
QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing"))
processing.alghelp(algOrName)
processing.algorithmHelp(algOrName)
return
i = 0
for param in alg.parameters:
Expand Down Expand Up @@ -302,7 +298,7 @@ def runAlgorithm(algOrName, onFinish, *args, **kwargs):
elif iface is not None:
feedback = MessageBarProgress(alg.name)

ret = runalg(alg, feedback)
ret = execute(alg, feedback)
if ret:
if onFinish is not None:
onFinish(alg, feedback)
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/core/ProcessingLog.py
Expand Up @@ -69,7 +69,7 @@ def addToLog(msgtype, msg):
with codecs.open(ProcessingLog.logFilename(), 'a',
encoding='utf-8') as logfile:
logfile.write(line)
algname = msg[len('Processing.runalg("'):]
algname = msg[len('processing.run("'):]
algname = algname[:algname.index('"')]
if algname not in ProcessingLog.recentAlgs:
ProcessingLog.recentAlgs.append(algname)
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/core/parameters.py
Expand Up @@ -160,7 +160,7 @@ def getValueAsCommandLineParameter(self):
"""
Returns the value of this parameter as it should have been
entered in the console if calling an algorithm using the
Processing.runalg() method.
processing.run() method.
"""
return str(self.value)

Expand Down
6 changes: 3 additions & 3 deletions python/plugins/processing/gui/AlgorithmDialog.py
Expand Up @@ -39,7 +39,7 @@

from processing.gui.BatchAlgorithmDialog import BatchAlgorithmDialog
from processing.gui.AlgorithmDialogBase import AlgorithmDialogBase
from processing.gui.AlgorithmExecutor import runalg, runalgIterating
from processing.gui.AlgorithmExecutor import execute, executeIterating
from processing.gui.Postprocessing import handleAlgorithmResults

from processing.core.parameters import ParameterRaster
Expand Down Expand Up @@ -198,7 +198,7 @@ def accept(self):
self.tr('<b>Algorithm {0} starting...</b>').format(self.alg.name))

if self.iterateParam:
if runalgIterating(self.alg, self.iterateParam, self.feedback):
if executeIterating(self.alg, self.iterateParam, self.feedback):
self.finish()
else:
QApplication.restoreOverrideCursor()
Expand All @@ -208,7 +208,7 @@ def accept(self):
if command:
ProcessingLog.addToLog(
ProcessingLog.LOG_ALGORITHM, command)
if runalg(self.alg, self.feedback):
if execute(self.alg, self.feedback):
self.finish()
else:
QApplication.restoreOverrideCursor()
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/processing/gui/AlgorithmExecutor.py
Expand Up @@ -42,7 +42,7 @@
from processing.tools import vector


def runalg(alg, feedback=None):
def execute(alg, feedback=None):
"""Executes a given algorithm, showing its progress in the
progress object passed along.
Expand All @@ -63,7 +63,7 @@ def runalg(alg, feedback=None):
return False


def runalgIterating(alg, paramToIter, feedback):
def executeIterating(alg, paramToIter, feedback):
# Generate all single-feature layers
settings = QgsSettings()
systemEncoding = settings.value('/UI/encoding', 'System')
Expand Down Expand Up @@ -96,7 +96,7 @@ def runalgIterating(alg, paramToIter, feedback):
out.value = filename
feedback.setProgressText(tr('Executing iteration {0}/{1}...').format(i, len(filelist)))
feedback.setProgress(i * 100 / len(filelist))
if runalg(alg, feedback):
if execute(alg, feedback):
handleAlgorithmResults(alg, None, False)
else:
return False
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/processing/gui/BatchAlgorithmDialog.py
Expand Up @@ -34,7 +34,7 @@

from processing.gui.BatchPanel import BatchPanel
from processing.gui.AlgorithmDialogBase import AlgorithmDialogBase
from processing.gui.AlgorithmExecutor import runalg
from processing.gui.AlgorithmExecutor import execute
from processing.gui.Postprocessing import handleAlgorithmResults

from processing.core.ProcessingResults import ProcessingResults
Expand Down Expand Up @@ -121,7 +121,7 @@ def accept(self):
for count, alg in enumerate(self.algs):
self.setText(self.tr('\nProcessing algorithm {0}/{1}...').format(count + 1, len(self.algs)))
self.setInfo(self.tr('<b>Algorithm {0} starting...</b>').format(alg.name))
if runalg(alg, self.feedback) and not self.canceled:
if execute(alg, self.feedback) and not self.canceled:
if self.load[count]:
handleAlgorithmResults(alg, self.feedback, False)
self.setInfo(self.tr('Algorithm {0} correctly executed...').format(alg.name))
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/gui/HistoryDialog.py
Expand Up @@ -114,7 +114,7 @@ def executeAlgorithm(self):
if isinstance(item, TreeLogEntryItem):
if item.isAlg:
script = 'import processing\n'
script += item.entry.text.replace('runalg(', 'runandload(')
script += item.entry.text.replace('run(', 'runAndLoadResults(')
exec(script)

def changeText(self):
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/processing/gui/ProcessingToolbox.py
Expand Up @@ -45,7 +45,7 @@
from processing.gui.EditRenderingStylesDialog import EditRenderingStylesDialog
from processing.gui.ConfigDialog import ConfigDialog
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.AlgorithmExecutor import runalg
from processing.gui.AlgorithmExecutor import execute
from processing.core.alglist import algList

pluginPath = os.path.split(os.path.dirname(__file__))[0]
Expand Down Expand Up @@ -274,7 +274,7 @@ def executeAlgorithm(self):
self.addRecentAlgorithms(True)
else:
feedback = MessageBarProgress()
runalg(alg, feedback)
execute(alg, feedback)
handleAlgorithmResults(alg, feedback)
feedback.close()
if isinstance(item, TreeActionItem):
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/gui/TestTools.py
Expand Up @@ -133,7 +133,7 @@ def parseParameters(command):
def createTest(text):
definition = {}

tokens = list(parseParameters(text[len('processing.runalg('):-1]))
tokens = list(parseParameters(text[len('processing.run('):-1]))
cmdname = tokens[0]
alg = Processing.getAlgorithm(cmdname)

Expand Down
4 changes: 2 additions & 2 deletions python/plugins/processing/gui/menus.py
Expand Up @@ -10,7 +10,7 @@
from qgis.utils import iface
from qgis.core import QgsApplication
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.AlgorithmExecutor import runalg
from processing.gui.AlgorithmExecutor import execute
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.core.Processing import Processing

Expand Down Expand Up @@ -221,7 +221,7 @@ def _executeAlgorithm(alg):
canvas.setMapTool(prevMapTool)
else:
feedback = MessageBarProgress()
runalg(alg, feedback)
execute(alg, feedback)
handleAlgorithmResults(alg, feedback)
feedback.close()

Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/modeler/ModelerAlgorithm.py
Expand Up @@ -152,7 +152,7 @@ def _toString(v):
params.append(safeName(self.outputs[out.name].description).lower())
else:
params.append(str(None))
s.append("outputs_%s=processing.runalg('%s', %s)" % (self.name, self.consoleName, ",".join(params)))
s.append("outputs_%s=processing.run('%s', %s)" % (self.name, self.consoleName, ",".join(params)))
return s


Expand Down
Expand Up @@ -5,12 +5,12 @@

import processing

result = processing.runalg("qgis:selectbyattribute",
INPUT_LAYER,
"id2",
0,
"2")
result = processing.run("qgis:selectbyattribute",
INPUT_LAYER,
"id2",
0,
"2")

processing.runalg("qgis:saveselectedfeatures",
result["OUTPUT"],
OUTPUT_LAYER)
processing.run("qgis:saveselectedfeatures",
result["OUTPUT"],
OUTPUT_LAYER)
61 changes: 44 additions & 17 deletions python/plugins/processing/tools/general.py
Expand Up @@ -41,50 +41,77 @@
from processing.gui.Postprocessing import handleAlgorithmResults


def alglist(text=None):
def algorithmsList(text=None):
"""Returns list of all available Processing algorithms or list
of algorithms which names contains given text.
Returned list contains algorithm command-line names.
"""
lst = []
for provider in list(algList.algs.values()):
sortedlist = sorted(list(provider.values()), key=lambda alg: alg.name)
for alg in sortedlist:
if text is None or text.lower() in alg.name.lower():
lst.append(alg.commandLineName())
return lst


def printAlgorithms(text=None):
"""Print list of all available Processing algorithms or list
of algorithms which names contains given text.
Prints algorithms user-friendly names as well as command-line
names.
"""
s = ''
for provider in list(algList.algs.values()):
sortedlist = sorted(list(provider.values()), key=lambda alg: alg.name)
for alg in sortedlist:
if text is None or text.lower() in alg.name.lower():
s += alg.name.ljust(50, '-') + '--->' + alg.commandLineName() \
+ '\n'
s += '{}--->{}\n'.format(alg.name.ljust(50, '-'), alg.commandLineName())
print(s)


def algoptions(name):
def algorithmOptions(name):
"""Prints all algorithm options with their values.
"""
alg = Processing.getAlgorithm(name)
if alg is not None:
s = ''
opts = ''
for param in alg.parameters:
if isinstance(param, ParameterSelection):
s += param.name + '(' + param.description + ')\n'
i = 0
for option in param.options:
s += '\t' + str(i) + ' - ' + str(option) + '\n'
i += 1
print(s)
opts += '{} ({})\n'.format(param.name, param.description)
for option in enumerate(param.options):
opts += '\t{} - {}\n'.format(option[0], option[1])
print(opts)
else:
print('Algorithm not found')
print('Algorithm "{}" not found.'.format(name))


def alghelp(name):
def algorithmHelp(name):
"""Prints algorithm parameters with their types. Also
provides information about options if any.
"""
alg = Processing.getAlgorithm(name)
if alg is not None:
alg = alg.getCopy()
print(str(alg))
algoptions(name)
algorithmOptions(name)
else:
print('Algorithm not found')
print('Algorithm "{}" not found.'.format(name))


def runalg(algOrName, *args, **kwargs):
def run(algOrName, *args, **kwargs):
"""Executes given algorithm and returns its outputs as dictionary
object.
"""
alg = Processing.runAlgorithm(algOrName, None, *args, **kwargs)
if alg is not None:
return alg.getOutputValuesAsDictionary()


def runandload(name, *args, **kwargs):
def runAndLoadResults(name, *args, **kwargs):
"""Executes given algorithm and load its results into QGIS project
when possible.
"""
return Processing.runAlgorithm(name, handleAlgorithmResults, *args, **kwargs)


Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/tools/help.py
Expand Up @@ -89,7 +89,7 @@ def baseHelpForAlgorithm(alg, folder):
f.write('Console usage\n')
f.write('-------------\n')
f.write('\n::\n\n')
cmd = " processing.runalg('{}', ".format(alg.commandLineName())
cmd = " processing.run('{}', ".format(alg.commandLineName())
for p in alg.parameters:
cmd += '{}, '.format(p.name.lower().strip())

Expand Down

0 comments on commit b8cb196

Please sign in to comment.