Skip to content

Commit 6173fa3

Browse files
committed
made SEXTANTE command line usage more pythonic
Fixed problem with temporary grass mapset created by SEXTANTE (wrong path)
1 parent 3398341 commit 6173fa3

File tree

9 files changed

+117
-73
lines changed

9 files changed

+117
-73
lines changed

python/plugins/sextante/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
***************************************************************************
1818
"""
1919

20+
from sextante.core.Sextante import runalg, alghelp, alglist, algoptions, load, loadFromAlg, extent, getObjectFromName, getObjectFromUri
21+
2022
__author__ = 'Victor Olaya'
2123
__date__ = 'August 2012'
2224
__copyright__ = '(C) 2012, Victor Olaya'

python/plugins/sextante/core/GeoAlgorithm.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ def getOutputValue(self, name):
264264
def getAsCommand(self):
265265
'''Returns the command that would run this same algorithm from the console.
266266
Should return null if the algorithm cannot be run from the console.'''
267-
s="Sextante.runalg(\"" + self.commandLineName() + "\","
267+
s="sextante.runalg(\"" + self.commandLineName() + "\","
268268
for param in self.parameters:
269269
s+=param.getValueAsCommandLineParameter() + ","
270270
for out in self.outputs:

python/plugins/sextante/core/Sextante.py

+80-59
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
from PyQt4.QtCore import *
2626
from PyQt4.QtGui import *
27-
27+
from qgis.core import *
2828
from sextante.core.QGisLayers import QGisLayers
2929
from sextante.core.SextanteConfig import SextanteConfig
3030
from sextante.core.GeoAlgorithm import GeoAlgorithm
@@ -238,45 +238,14 @@ def getAlgorithm(name):
238238
return provider[name]
239239
return None
240240

241-
242-
##This methods are here to be used from the python console,
243-
##making it easy to use SEXTANTE from there
244-
##==========================================================
245-
246-
@staticmethod
247-
def alglist(text=None):
248-
s=""
249-
for provider in Sextante.algs.values():
250-
sortedlist = sorted(provider.values(), key= lambda alg: alg.name)
251-
for alg in sortedlist:
252-
if text == None or text.lower() in alg.name.lower():
253-
s+=(alg.name.ljust(50, "-") + "--->" + alg.commandLineName() + "\n")
254-
print s
255-
256-
257241
@staticmethod
258-
def algoptions(name):
259-
alg = Sextante.getAlgorithm(name)
260-
if alg != None:
261-
s =""
262-
for param in alg.parameters:
263-
if isinstance(param, ParameterSelection):
264-
s+=param.name + "(" + param.description + ")\n"
265-
i=0
266-
for option in param.options:
267-
s+= "\t" + str(i) + " - " + str(option) + "\n"
268-
i+=1
269-
print(s)
270-
else:
271-
print "Algorithm not found"
242+
def getObject(uri):
243+
'''Returns the QGIS object identified by the given URI'''
244+
return QGisLayers.getObjectFromUri(uri)
272245

273246
@staticmethod
274-
def alghelp(name):
275-
alg = Sextante.getAlgorithm(name)
276-
if alg != None:
277-
print(str(alg))
278-
else:
279-
print "Algorithm not found"
247+
def runandload(name, *args):
248+
Sextante.runAlgorithm(name, SextantePostprocessing.handleAlgorithmResults, *args)
280249

281250
@staticmethod
282251
def runAlgorithm(algOrName, onFinish, *args):
@@ -359,28 +328,80 @@ def cancel():
359328
QApplication.restoreOverrideCursor()
360329
return alg
361330

362-
@staticmethod
363-
def runalg(algOrName, *args):
364-
alg = Sextante.runAlgorithm(algOrName, None, *args)
365-
return alg.getOutputValuesAsDictionary()
366-
367331

368-
@staticmethod
369-
def load(layer):
370-
'''Loads a layer into QGIS'''
371-
QGisLayers.load(layer)
332+
##==========================================================
333+
##This methods are here to be used from the python console,
334+
##making it easy to use SEXTANTE from there
335+
##==========================================================
372336

373-
@staticmethod
374-
def loadFromAlg(layersdict):
375-
'''Load all layer resulting from a given algorithm.
376-
Layers are passed as a dictionary, obtained from alg.getOutputValuesAsDictionary()'''
377-
QGisLayers.loadFromDict(layersdict)
378337

379-
@staticmethod
380-
def getObject(uri):
381-
'''Returns the QGIS object identified by the given URI'''
382-
return QGisLayers.getObjectFromUri(uri)
383-
384-
@staticmethod
385-
def runandload(name, *args):
386-
Sextante.runAlgorithm(name, SextantePostprocessing.handleAlgorithmResults, *args)
338+
def alglist(text=None):
339+
s=""
340+
for provider in Sextante.algs.values():
341+
sortedlist = sorted(provider.values(), key= lambda alg: alg.name)
342+
for alg in sortedlist:
343+
if text == None or text.lower() in alg.name.lower():
344+
s+=(alg.name.ljust(50, "-") + "--->" + alg.commandLineName() + "\n")
345+
print s
346+
347+
def algoptions(name):
348+
alg = Sextante.getAlgorithm(name)
349+
if alg != None:
350+
s =""
351+
for param in alg.parameters:
352+
if isinstance(param, ParameterSelection):
353+
s+=param.name + "(" + param.description + ")\n"
354+
i=0
355+
for option in param.options:
356+
s+= "\t" + str(i) + " - " + str(option) + "\n"
357+
i+=1
358+
print(s)
359+
else:
360+
print "Algorithm not found"
361+
362+
def alghelp(name):
363+
alg = Sextante.getAlgorithm(name)
364+
if alg != None:
365+
print(str(alg))
366+
else:
367+
print "Algorithm not found"
368+
369+
def runalg(algOrName, *args):
370+
alg = Sextante.runAlgorithm(algOrName, None, *args)
371+
return alg.getOutputValuesAsDictionary()
372+
373+
def extent(layers):
374+
first = True
375+
for layer in layers:
376+
if not isinstance(layer, (QgsRasterLayer, QgsVectorLayer)):
377+
layer = QGisLayers.getObjectFromUri(layer)
378+
if first:
379+
xmin = layer.extent().xMinimum()
380+
xmax = layer.extent().xMaximum()
381+
ymin = layer.extent().yMinimum()
382+
ymax = layer.extent().yMaximum()
383+
else:
384+
xmin = min(xmin, layer.extent().xMinimum())
385+
xmax = max(xmax, layer.extent().xMaximum())
386+
ymin = min(ymin, layer.extent().yMinimum())
387+
ymax = max(ymax, layer.extent().yMaximum())
388+
first = False
389+
return str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str(ymax)
390+
391+
def getObjectFromName(name):
392+
layers = QGisLayers.getAllLayers()
393+
for layer in layers:
394+
if layer.name() == name:
395+
return layer
396+
397+
def getObjectFromUri(uri):
398+
return QGisLayers.getObjectFromUri(uri, False)
399+
400+
def load(layer):
401+
'''Loads a layer into QGIS'''
402+
QGisLayers.load(layer)
403+
404+
def loadFromAlg(layersdict):
405+
'''Load all layer resulting from a given algorithm.
406+
Layers are passed as a dictionary, obtained from alg.getOutputValuesAsDictionary()'''
407+
QGisLayers.loadFromDict(layersdict)

python/plugins/sextante/grass/GrassUtils.py

+13-5
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
* *
1717
***************************************************************************
1818
"""
19+
from PyQt4 import QtGui
1920

2021
__author__ = 'Victor Olaya'
2122
__date__ = 'August 2012'
@@ -129,7 +130,8 @@ def createGrassScript(commands):
129130
output = open(gisrc, "w")
130131
location = "temp_location"
131132
mapset = "user"
132-
gisdbase = os.path.join(os.path.expanduser("~"), "sextante", "tempdata", "grassdata")
133+
gisdbase = GrassUtils.grassDataFolder()
134+
#gisdbase = os.path.join(os.path.expanduser("~"), "sextante", "tempdata", "grassdata")
133135
output.write("GISDBASE: " + gisdbase + "\n");
134136
output.write("LOCATION_NAME: " + location + "\n");
135137
output.write("MAPSET: " + mapset + "\n");
@@ -178,7 +180,13 @@ def createGrassBatchJobFileFromGrassCommands(commands):
178180

179181
@staticmethod
180182
def grassMapsetFolder():
181-
tempfolder = os.path.join(SextanteUtils.tempFolder(), "grassdata", "temp_location")
183+
folder = os.path.join(GrassUtils.grassDataFolder(), "temp_location")
184+
mkdir(folder)
185+
return folder
186+
187+
@staticmethod
188+
def grassDataFolder():
189+
tempfolder = os.path.join(SextanteUtils.tempFolder(), "grassdata")
182190
mkdir(tempfolder)
183191
return tempfolder
184192

@@ -190,7 +198,7 @@ def createTempMapset():
190198
structure and content will vary slightly depending on whether the user wants to process lat/lon or x/y data.'''
191199

192200
latlon = SextanteConfig.getSetting(GrassUtils.GRASS_LATLON)
193-
folder = GrassUtils.grassMapsetFolder()
201+
folder = GrassUtils.grassMapsetFolder()
194202
mkdir(os.path.join(folder, "PERMANENT"))
195203
mkdir(os.path.join(folder, "user"))
196204
mkdir(os.path.join(folder, "PERMANENT", ".tmp"))
@@ -309,15 +317,15 @@ def getGrassVersion():
309317
# of the previous ones.
310318
# Starting a session just involves creating the temp mapset structure
311319
@staticmethod
312-
def startGrassSession():
320+
def startGrassSession():
313321
if not GrassUtils.sessionRunning:
314322
GrassUtils.createTempMapset()
315323
GrassUtils.sessionRunning = True
316324

317325
# End session by removing the temporary GRASS mapset and all the layers.
318326
@staticmethod
319327
def endGrassSession():
320-
shutil.rmtree(GrassUtils.grassMapsetFolder(), True)
328+
#shutil.rmtree(GrassUtils.grassMapsetFolder(), True)
321329
GrassUtils.sessionRunning = False
322330
GrassUtils.sessionLayers = {}
323331

python/plugins/sextante/gui/AlgorithmExecutor.py

-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,6 @@ def raiseInternalError(self, error):
9393
def runalg(self):
9494
try:
9595
self.algorithm.execute(self.progress)
96-
self.finished.emit()
9796
except GeoAlgorithmExecutionException, e :
9897
self.error.emit(e.msg)
9998
except BaseException, e:

python/plugins/sextante/outputs/Output.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def serialize(self):
5858

5959
def setValue(self, value):
6060
try:
61-
if value != None:
61+
if value != None and isinstance(value, basestring):
6262
value = value.strip()
6363
self.value = value
6464
return True

python/plugins/sextante/saga/SagaUtils.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,10 @@ def executeSaga(progress):
9595
for line in iter(proc.readline, ""):
9696
if "%" in line:
9797
s = "".join([x for x in line if x.isdigit()])
98-
progress.setPercentage(int(s))
98+
try:
99+
progress.setPercentage(int(s))
100+
except:
101+
pass
99102
else:
100103
line = line.strip()
101104
if line!="/" and line!="-" and line !="\\" and line!="|":

python/plugins/sextante/script/ScriptAlgorithm.py

+15-4
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,10 @@ def processParameterLine(self,line):
161161
out = OutputHTML()
162162
elif tokens[1].lower().strip().startswith("output file"):
163163
out = OutputFile()
164+
elif tokens[1].lower().strip().startswith("output number"):
165+
out = OutputNumber()
166+
elif tokens[1].lower().strip().startswith("output string"):
167+
out = OutputString()
164168

165169
if param != None:
166170
self.addParameter(param)
@@ -173,18 +177,25 @@ def processParameterLine(self,line):
173177

174178
def processAlgorithm(self, progress):
175179

176-
script = "from sextante.core.Sextante import Sextante\n"
180+
script = "import sextante\n"
181+
182+
ns = {}
183+
177184
for param in self.parameters:
178-
script += param.name + "=" + param.getValueAsCommandLineParameter() + "\n"
185+
#script += param.name + "=" + param.getValueAsCommandLineParameter() + "\n"
186+
ns[param.name] = param.value
179187

180188
for out in self.outputs:
181-
script += out.name + "=" + out.getValueAsCommandLineParameter() + "\n"
189+
ns[out.name] = out.value
190+
#script += out.name + "=" + out.getValueAsCommandLineParameter() + "\n"
182191

183192
script+=self.script
184193
redirection = Redirection(progress)
185194
sys.stdout = redirection
186-
exec(script)
195+
exec(script) in ns
187196
sys.stdout = sys.__stdout__
197+
for out in self.outputs:
198+
out.setValue(ns[out.name])
188199

189200
def helpFile(self):
190201
helpfile = self.descriptionFile + ".help"

python/plugins/sextante/script/scripts/Hex_grid_from_layer_bounds.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@
99
centery = (input.extent().yMinimum() + input.extent().yMaximum()) / 2
1010
width = (input.extent().xMaximum() - input.extent().xMinimum())
1111
height = (input.extent().yMaximum() - input.extent().yMinimum())
12-
Sextante.runalg("mmqgisx:creategrid", cellsize, cellsize, width, height, centerx, centery, 3, grid)
12+
sextante.runalg("mmqgisx:creategrid", cellsize, cellsize, width, height, centerx, centery, 3, grid)

0 commit comments

Comments
 (0)