本文整理汇总了Python中qgis.core.QgsProcessingUtils.generateTempFilename方法的典型用法代码示例。如果您正苦于以下问题:Python QgsProcessingUtils.generateTempFilename方法的具体用法?Python QgsProcessingUtils.generateTempFilename怎么用?Python QgsProcessingUtils.generateTempFilename使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qgis.core.QgsProcessingUtils
的用法示例。
在下文中一共展示了QgsProcessingUtils.generateTempFilename方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: exportRasterLayer
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def exportRasterLayer(self, parameterName, layer):
global sessionExportedLayers
if layer.source() in sessionExportedLayers:
exportedLayer = sessionExportedLayers[layer.source()]
if os.path.exists(exportedLayer):
self.exportedLayers[parameterName] = exportedLayer
return None
else:
del sessionExportedLayers[layer.source()]
if layer:
filename = layer.name()
else:
filename = os.path.basename(layer.source())
validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:'
filename = ''.join(c for c in filename if c in validChars)
if len(filename) == 0:
filename = 'layer'
destFilename = QgsProcessingUtils.generateTempFilename(filename + '.sgrd')
sessionExportedLayers[layer.source()] = destFilename
self.exportedLayers[parameterName] = destFilename
return 'io_gdal 0 -TRANSFORM 1 -RESAMPLING 3 -GRIDS "{}" -FILES "{}"'.format(destFilename, layer.source())
示例2: writeLayerParameterToTextFile
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def writeLayerParameterToTextFile(filename, alg, parameters, parameter_name, context, quote=True, executing=False):
listFile = QgsProcessingUtils.generateTempFilename(filename)
with open(listFile, 'w') as f:
if executing:
layers = []
for l in alg.parameterAsLayerList(parameters, parameter_name, context):
if quote:
layers.append('"' + l.source() + '"')
else:
layers.append(l.source())
f.write('\n'.join(layers))
return listFile
示例3: exportVectorLayer
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def exportVectorLayer(layer, supported=None):
"""Takes a QgsVectorLayer and returns the filename to refer to it,
which allows external apps which support only file-based layers to
use it. It performs the necessary export in case the input layer
is not in a standard format suitable for most applications, it is
a remote one or db-based (non-file based) one, or if there is a
selection and it should be used, exporting just the selected
features.
Currently, the output is restricted to shapefiles, so anything
that is not in a shapefile will get exported. It also export to
a new file if the original one contains non-ascii characters.
"""
supported = supported or ["shp"]
settings = QgsSettings()
systemEncoding = settings.value('/UI/encoding', 'System')
output = getTempFilename('shp')
basename = removeInvalidChars(os.path.basename(layer.source()))
if basename:
if not basename.endswith("shp"):
basename = os.path.splitext(basename)[0] + ".shp"
output = QgsProcessingUtils.generateTempFilename(basename)
else:
output = getTempFilename("shp")
useSelection = False # TODO ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
if useSelection and layer.selectedFeatureCount() != 0:
writer = QgsVectorFileWriter(output, systemEncoding,
layer.fields(),
layer.wkbType(), layer.crs())
selection = layer.selectedFeatures()
for feat in selection:
writer.addFeature(feat, QgsFeatureSink.FastInsert)
del writer
return output
else:
if not os.path.splitext(layer.source())[1].lower() in supported:
writer = QgsVectorFileWriter(
output, systemEncoding,
layer.fields(), layer.wkbType(),
layer.crs()
)
for feat in layer.getFeatures():
writer.addFeature(feat, QgsFeatureSink.FastInsert)
del writer
return output
else:
return layer.source()
示例4: getCompatibleFileName
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def getCompatibleFileName(self, alg):
"""Returns a filename that is compatible with the algorithm
that is going to generate this output.
If the algorithm supports the file format of the current
output value, it returns that value. If not, it returns a
temporary file with a supported file format, to be used to
generate the output result.
"""
ext = self.value[self.value.rfind('.') + 1:]
if ext in alg.provider().supportedOutputTableExtensions():
return self.value
else:
if self.compatible is None:
self.compatible = QgsProcessingUtils.generateTempFilename(
self.name + '.' + alg.provider().supportedOutputTableExtensions()[0])
return self.compatible
示例5: exportRasterLayer
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def exportRasterLayer(self, source):
global sessionExportedLayers
if source in sessionExportedLayers:
self.exportedLayers[source] = sessionExportedLayers[source]
return None
fileName = os.path.basename(source)
validChars = \
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
fileName = ''.join(c for c in fileName if c in validChars)
if len(fileName) == 0:
fileName = 'layer'
destFilename = QgsProcessingUtils.generateTempFilename("{}.asc".format(fileName))
self.exportedLayers[source] = destFilename
sessionExportedLayers[source] = destFilename
return "gdal_translate -of AAIGrid {} {}".format(source, destFilename)
示例6: exportRasterLayer
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def exportRasterLayer(self, source):
global sessionExportedLayers
context = dataobjects.createContext()
if source in sessionExportedLayers:
exportedLayer = sessionExportedLayers[source]
if os.path.exists(exportedLayer):
self.exportedLayers[source] = exportedLayer
return None
else:
del sessionExportedLayers[source]
layer = QgsProcessingUtils.mapLayerFromString(source, context, False)
if layer:
filename = str(layer.name())
else:
filename = os.path.basename(source)
validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:'
filename = ''.join(c for c in filename if c in validChars)
if len(filename) == 0:
filename = 'layer'
destFilename = QgsProcessingUtils.generateTempFilename(filename + '.sgrd')
self.exportedLayers[source] = destFilename
sessionExportedLayers[source] = destFilename
return 'io_gdal 0 -TRANSFORM 1 -RESAMPLING 3 -GRIDS "' + destFilename + '" -FILES "' + source + '"'
示例7: _resolveTemporary
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def _resolveTemporary(self, alg):
ext = self.getDefaultFileExtension()
return QgsProcessingUtils.generateTempFilename(self.name + '.' + ext)
示例8: processAlgorithm
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
#.........这里部分代码省略.........
else:
command += ' -{} false'.format(param.name().strip())
elif isinstance(param, QgsProcessingParameterMatrix):
tempTableFile = getTempFilename('txt')
with open(tempTableFile, 'w') as f:
f.write('\t'.join([col for col in param.headers()]) + '\n')
values = self.parameterAsMatrix(parameters, param.name(), context)
for i in range(0, len(values), 3):
s = '{}\t{}\t{}\n'.format(values[i], values[i + 1], values[i + 2])
f.write(s)
command += ' -{} "{}"'.format(param.name(), tempTableFile)
elif isinstance(param, QgsProcessingParameterExtent):
# 'We have to substract/add half cell size, since SAGA is
# center based, not corner based
halfcell = self.getOutputCellsize(parameters, context) / 2
offset = [halfcell, -halfcell, halfcell, -halfcell]
rect = self.parameterAsExtent(parameters, param.name(), context)
values = []
values.append(rect.xMinimum())
values.append(rect.xMaximum())
values.append(rect.yMinimum())
values.append(rect.yMaximum())
for i in range(4):
command += ' -{} {}'.format(param.name().split(' ')[i], float(values[i]) + offset[i])
elif isinstance(param, QgsProcessingParameterNumber):
if param.dataType() == QgsProcessingParameterNumber.Integer:
command += ' -{} {}'.format(param.name(), self.parameterAsInt(parameters, param.name(), context))
else:
command += ' -{} {}'.format(param.name(), self.parameterAsDouble(parameters, param.name(), context))
elif isinstance(param, QgsProcessingParameterEnum):
command += ' -{} {}'.format(param.name(), self.parameterAsEnum(parameters, param.name(), context))
elif isinstance(param, (QgsProcessingParameterString, QgsProcessingParameterFile)):
command += ' -{} "{}"'.format(param.name(), self.parameterAsFile(parameters, param.name(), context))
elif isinstance(param, (QgsProcessingParameterString, QgsProcessingParameterField)):
command += ' -{} "{}"'.format(param.name(), self.parameterAsString(parameters, param.name(), context))
output_layers = []
output_files = {}
#If the user has entered an output file that has non-ascii chars, we use a different path with only ascii chars
output_files_nonascii = {}
for out in self.destinationParameterDefinitions():
filePath = self.parameterAsOutputLayer(parameters, out.name(), context)
if isinstance(out, (QgsProcessingParameterRasterDestination, QgsProcessingParameterVectorDestination)):
output_layers.append(filePath)
try:
filePath.encode('ascii')
except UnicodeEncodeError:
nonAsciiFilePath = filePath
filePath = QgsProcessingUtils.generateTempFilename(out.name() + os.path.splitext(filePath)[1])
output_files_nonascii[filePath] = nonAsciiFilePath
output_files[out.name()] = filePath
command += ' -{} "{}"'.format(out.name(), filePath)
commands.append(command)
# special treatment for RGB algorithm
# TODO: improve this and put this code somewhere else
for out in self.destinationParameterDefinitions():
if isinstance(out, QgsProcessingParameterRasterDestination):
filename = self.parameterAsOutputLayer(parameters, out.name(), context)
filename2 = os.path.splitext(filename)[0] + '.sgrd'
if self.cmdname == 'RGB Composite':
commands.append('io_grid_image 0 -COLOURING 4 -GRID:"{}" -FILE:"{}"'.format(filename2, filename))
# 3: Run SAGA
commands = self.editCommands(commands)
SagaUtils.createSagaBatchJobFileFromSagaCommands(commands)
loglines = []
loglines.append(self.tr('SAGA execution commands'))
for line in commands:
feedback.pushCommandInfo(line)
loglines.append(line)
if ProcessingConfig.getSetting(SagaUtils.SAGA_LOG_COMMANDS):
QgsMessageLog.logMessage('\n'.join(loglines), self.tr('Processing'), Qgis.Info)
SagaUtils.executeSaga(feedback)
if crs is not None:
for out in output_layers:
prjFile = os.path.splitext(out)[0] + '.prj'
with open(prjFile, 'w') as f:
f.write(crs.toWkt())
for old, new in output_files_nonascii.items():
oldFolder = os.path.dirname(old)
newFolder = os.path.dirname(new)
newName = os.path.splitext(os.path.basename(new))[0]
files = [f for f in os.listdir(oldFolder)]
for f in files:
ext = os.path.splitext(f)[1]
newPath = os.path.join(newFolder, newName + ext)
oldPath = os.path.join(oldFolder, f)
shutil.move(oldPath, newPath)
result = {}
for o in self.outputDefinitions():
if o.name() in output_files:
result[o.name()] = output_files[o.name()]
return result
示例9: processAlgorithm
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def processAlgorithm(self, parameters, context, feedback):
arguments = []
toolPath = prepairUtils.prepairPath()
if toolPath == "":
toolPath = self.name()
arguments.append(toolPath)
paradigm = self.parameterAsEnum(parameters, self.PARADIGM, context)
if paradigm == 1:
arguments.append("--setdiff")
minArea = self.parameterAsDouble(parameters, self.MIN_AREA, context)
if minArea > 0.0:
arguments.append("--minarea")
arguments.append("{}".format(minArea))
snapRounding = self.parameterAsInt(parameters, self.SNAP_ROUNDING, context)
if snapRounding > 0:
arguments.append("--isr")
arguments.append("{}".format(snapRounding))
onlyInvalid = self.parameterAsBool(parameters, self.ONLY_INVALID, context)
tmpFile = QgsProcessingUtils.generateTempFilename("prepair.shp")
arguments.append("-f")
arguments.append(tmpFile)
source = self.parameterAsSource(parameters, self.INPUT, context)
(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
source.fields(), source.wkbType(), source.sourceCrs())
features = source.getFeatures(QgsFeatureRequest(), QgsProcessingFeatureSource.FlagSkipGeometryValidityChecks)
total = 100.0 / source.featureCount() if source.featureCount() else 0
for current, feat in enumerate(features):
if feedback.isCanceled():
break
geom = feat.geometry()
if onlyInvalid and len(geom.validateGeometry()) == 0:
feedback.pushInfo(
self.tr("Feature {} is valid, skipping…".format(feat.id())))
feedback.setProgress(int(count * total))
continue
with open(tmpFile, "w") as f:
f.write(geom.asWkt())
result = prepairUtils.execute(arguments, feedback)
if len(result) == 0:
feedback.poushInfo(self.tr("Feature {} not repaired".format(feat.id())))
feedback.setProgress(int(count * total))
continue
geom = QgsGeometry.fromWkt(result[0].strip())
if geom is None or geom.isEmpty():
feedback.pushInfo(self.tr("Empty geometry after repairing "
"feature {}, skipping…".format(feat.id())))
feedback.setProgress(int(count * total))
continue
feat.setGeometry(geom)
sink.addFeature(feat, QgsFeatureSink.FastInsert)
feedback.setProgress(int(current * total))
return {self.OUTPUT: dest_id}
示例10: writeConfiguration
# 需要导入模块: from qgis.core import QgsProcessingUtils [as 别名]
# 或者: from qgis.core.QgsProcessingUtils import generateTempFilename [as 别名]
def writeConfiguration():
cfg = configparser.ConfigParser()
cfg["Options for advanced mode"] = {}
section = cfg["Options for advanced mode"]
section["ground_file_is_resistances"] = "True"
section["remove_src_or_gnd"] = "keepall"
section["ground_file"] = ""
section["use_unit_currents"] = "False"
section["source_file"] = ""
section["use_direct_grounds"] = "False"
cfg["Mask file"] = {}
section = cfg["Mask file"]
section["mask_file"] = ""
section["use_mask"] = "False"
cfg["Calculation options"] = {}
section = cfg["Calculation options"]
section["low_memory_mode"] = "False"
section["parallelize"] = "False"
section["solver"] = "cg+amg"
section["print_timings"] = "True"
section["preemptive_memory_release"] = str(ProcessingConfig.getSetting(PREEMPT_MEMORY))
section["print_rusages"] = "False"
section["max_parallel"] = "0"
cfg["Short circuit regions (aka polygons)"] = {}
section = cfg["Short circuit regions (aka polygons)"]
section["polygon_file"] = ""
section["use_polygons"] = "False"
cfg["Options for one-to-all and all-to-one modes"] = {}
section = cfg["Options for one-to-all and all-to-one modes"]
section["use_variable_source_strengths"] = "False"
section["variable_source_file"] = ""
cfg["Output options"] = {}
section = cfg["Output options"]
section["set_null_currents_to_nodata"] = "False"
section["set_focal_node_currents_to_zero"] = str(ProcessingConfig.getSetting(ZERO_FOCAL))
section["set_null_voltages_to_nodata"] = "False"
section["compress_grids"] = str(ProcessingConfig.getSetting(COMPRESS_OUTPUT))
section["write_cur_maps"] = "True"
section["write_volt_maps"] = "True"
section["output_file"] = ""
section["write_cum_cur_map_only"] = str(ProcessingConfig.getSetting(CUM_MAX_MAPS))
section["log_transform_maps"] = str(ProcessingConfig.getSetting(LOG_TRANSFORM))
section["write_max_cur_maps"] = str(ProcessingConfig.getSetting(MAX_CURRENT_MAPS))
cfg["Options for reclassification of habitat data"] = {}
section = cfg["Options for reclassification of habitat data"]
section["reclass_file"] = ""
section["use_reclass_table"] = "False"
cfg["Logging Options"] = {}
section = cfg["Logging Options"]
section["log_level"] = "INFO"
section["log_file"] = "None"
section["profiler_log_file"] = "None"
section["screenprint_log"] = "False"
cfg["Options for pairwise and one-to-all and all-to-one modes"] = {}
section = cfg["Options for pairwise and one-to-all and all-to-one modes"]
section["included_pairs_file"] = ""
section["use_included_pairs"] = "False"
section["point_file"] = ""
cfg["Connection scheme for raster habitat data"] = {}
section = cfg["Connection scheme for raster habitat data"]
section["connect_using_avg_resistances"] = str(ProcessingConfig.getSetting(AVERAGE_CONDUCTANCE))
section["connect_four_neighbors_only"] = str(ProcessingConfig.getSetting(FOUR_NEIGHBOURS))
cfg["Habitat raster or graph"] = {}
section = cfg["Habitat raster or graph"]
section["habitat_map_is_resistances"] = "True"
section["Habitat raster or graph"] = "habitat_file"
cfg["Circuitscape mode"] = {}
section["data_type"] = "raster"
section["scenario"] = ""
iniPath = QgsProcessingUtils.generateTempFilename("circuitscape.ini")
with open(iniPath, "w") as f:
cfg.write(f)
return iniPath