本文整理汇总了Python中PyQt.QtCore.QDir.tempPath方法的典型用法代码示例。如果您正苦于以下问题:Python QDir.tempPath方法的具体用法?Python QDir.tempPath怎么用?Python QDir.tempPath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt.QtCore.QDir
的用法示例。
在下文中一共展示了QDir.tempPath方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def __init__(self, parent, plugin):
QDialog.__init__(self, parent)
self.setupUi(self)
self.plugin = plugin
self.mResult = ""
self.progressBar.setRange(0, 0)
self.progressBar.setFormat("%p%")
self.labelName.setText(plugin["name"])
self.buttonBox.clicked.connect(self.abort)
url = QUrl(plugin["download_url"])
fileName = plugin["filename"]
tmpDir = QDir.tempPath()
tmpPath = QDir.cleanPath(tmpDir + "/" + fileName)
self.file = QFile(tmpPath)
self.request = QNetworkRequest(url)
authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"]
if authcfg and isinstance(authcfg, basestring):
if not QgsAuthManager.instance().updateNetworkRequest(
self.request, authcfg.strip()):
self.mResult = self.tr(
"Update of network request with authentication "
"credentials FAILED for configuration '{0}'").format(authcfg)
self.request = None
if self.request is not None:
self.reply = QgsNetworkAccessManager.instance().get(self.request)
self.reply.downloadProgress.connect(self.readProgress)
self.reply.finished.connect(self.requestFinished)
self.stateChanged(4)
示例2: testComposition
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testComposition(self, page=0, pixelDiff=0):
if self.mComposition is None:
myMessage = "Composition not valid"
return False, myMessage
# load expected image
self.setControlName("expected_" + self.mTestName)
# get width/height, create image and render the composition to it
outputImage = QImage(self.mSize, QImage.Format_RGB32)
self.mComposition.setPlotStyle(QgsComposition.Print)
outputImage.setDotsPerMeterX(self.mDotsPerMeter)
outputImage.setDotsPerMeterY(self.mDotsPerMeter)
QgsMultiRenderChecker.drawBackground(outputImage)
p = QPainter(outputImage)
self.mComposition.renderPage(p, page)
p.end()
renderedFilePath = QDir.tempPath() + QDir.separator() + QFileInfo(self.mTestName).baseName() + "_rendered.png"
outputImage.save(renderedFilePath, "PNG")
self.setRenderedImage(renderedFilePath)
testResult = self.runTest(self.mTestName, pixelDiff)
return testResult, self.report()
示例3: testDateTimeWriteShapefile
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testDateTimeWriteShapefile(self):
"""Check writing date and time fields to an ESRI shapefile."""
ml = QgsVectorLayer(
('Point?crs=epsg:4326&field=id:int&'
'field=date_f:date&field=time_f:time&field=dt_f:datetime'),
'test',
'memory')
assert ml is not None, 'Provider not initialized'
assert ml.isValid(), 'Source layer not valid'
provider = ml.dataProvider()
assert provider is not None
ft = QgsFeature()
ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10)))
ft.setAttributes([1, QDate(2014, 3, 5), QTime(13, 45, 22), QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22))])
res, features = provider.addFeatures([ft])
assert res
assert len(features) > 0
dest_file_name = os.path.join(str(QDir.tempPath()), 'datetime.shp')
print(dest_file_name)
crs = QgsCoordinateReferenceSystem()
crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
write_result = QgsVectorFileWriter.writeAsVectorFormat(
ml,
dest_file_name,
'utf-8',
crs,
'ESRI Shapefile')
self.assertEqual(write_result, QgsVectorFileWriter.NoError)
# Open result and check
created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr')
fields = created_layer.dataProvider().fields()
self.assertEqual(fields.at(fields.indexFromName('date_f')).type(), QVariant.Date)
#shapefiles do not support time types, result should be string
self.assertEqual(fields.at(fields.indexFromName('time_f')).type(), QVariant.String)
#shapefiles do not support datetime types, result should be string
self.assertEqual(fields.at(fields.indexFromName('dt_f')).type(), QVariant.String)
f = created_layer.getFeatures(QgsFeatureRequest()).next()
date_idx = created_layer.fieldNameIndex('date_f')
assert isinstance(f.attributes()[date_idx], QDate)
self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5))
time_idx = created_layer.fieldNameIndex('time_f')
#shapefiles do not support time types
assert isinstance(f.attributes()[time_idx], basestring)
self.assertEqual(f.attributes()[time_idx], '13:45:22')
#shapefiles do not support datetime types
datetime_idx = created_layer.fieldNameIndex('dt_f')
assert isinstance(f.attributes()[datetime_idx], basestring)
self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)).toString("yyyy/MM/dd hh:mm:ss.zzz"))
示例4: testPrintMapFromTemplate
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testPrintMapFromTemplate(self):
"""Test that we can get a map to render in the template."""
myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
myFileInfo = QFileInfo(myPath)
myRasterLayer = QgsRasterLayer(myFileInfo.filePath(),
myFileInfo.completeBaseName())
myRenderer = QgsMultiBandColorRenderer(
myRasterLayer.dataProvider(), 2, 3, 4
)
#mRasterLayer.setRenderer( rasterRenderer )
myPipe = myRasterLayer.pipe()
assert myPipe.set(myRenderer), "Cannot set pipe renderer"
QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer])
myMapRenderer = QgsMapRenderer()
myLayerStringList = []
myLayerStringList.append(myRasterLayer.id())
myMapRenderer.setLayerSet(myLayerStringList)
myMapRenderer.setProjectionsEnabled(False)
myComposition = QgsComposition(myMapRenderer)
myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent)
myComposition.loadFromTemplate(myDocument)
# now render the map, first zooming to the raster extents
myMap = myComposition.getComposerMapById(0)
myMessage = ('Map 0 could not be found in template %s', myFile)
assert myMap is not None, myMessage
myExtent = myRasterLayer.extent()
myMap.setNewExtent(myExtent)
myImagePath = os.path.join(str(QDir.tempPath()),
'template_map_render_python.png')
myPageNumber = 0
myImage = myComposition.printPageAsRaster(myPageNumber)
myImage.save(myImagePath)
assert os.path.exists(myImagePath), 'Map render was not created.'
# Not sure if this is a predictable way to test but its quicker than
# rendering.
myFileSize = QFileInfo(myImagePath).size()
myExpectedFileSize = 100000
myMessage = ('Expected file size to be greater than %s, got %s'
' for %s' %
(myExpectedFileSize, myFileSize, myImagePath))
assert myFileSize > myExpectedFileSize, myMessage
示例5: imageCheck
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def imageCheck(self, name, reference_image, image):
self.report += "<h2>Render {}</h2>\n".format(name)
temp_dir = QDir.tempPath() + '/'
file_name = temp_dir + 'symbol_' + name + ".png"
image.save(file_name, "PNG")
checker = QgsRenderChecker()
checker.setControlPathPrefix("symbolv2")
checker.setControlName("expected_" + reference_image)
checker.setRenderedImage(file_name)
checker.setColorTolerance(2)
result = checker.compareImages(name, 20)
self.report += checker.report()
print(self.report)
return result
示例6: testWrite
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testWrite(self):
for name in glob.glob("%s/raster/*.tif" % self.testDataDir):
baseName = os.path.basename(name)
allOk = True
ok = self.write("raster/%s" % baseName)
if not ok:
allOk = False
reportFilePath = "%s/qgistest.html" % QDir.tempPath()
reportFile = open(reportFilePath, 'a')
reportFile.write(self.report)
reportFile.close()
assert allOk, "Raster file writer test failed"
示例7: testStatistics
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testStatistics(self):
"""Test zonal stats"""
TEST_DATA_DIR = unitTestDataPath() + "/zonalstatistics/"
myTempPath = QDir.tempPath() + "/"
testDir = QDir(TEST_DATA_DIR)
for f in testDir.entryList(QDir.Files):
QFile.remove(myTempPath + f)
QFile.copy(TEST_DATA_DIR + f, myTempPath + f)
myVector = QgsVectorLayer(myTempPath + "polys.shp", "poly", "ogr")
myRasterPath = myTempPath + "edge_problem.asc"
zs = QgsZonalStatistics(myVector, myRasterPath, "", 1)
zs.calculateStatistics(None)
feat = QgsFeature()
# validate statistics for each feature
request = QgsFeatureRequest().setFilterFid(0)
feat = next(myVector.getFeatures(request))
myMessage = ('Expected: %f\nGot: %f\n' % (12.0, feat[1]))
assert feat[1] == 12.0, myMessage
myMessage = ('Expected: %f\nGot: %f\n' % (8.0, feat[2]))
assert feat[2] == 8.0, myMessage
myMessage = ('Expected: %f\nGot: %f\n' % (0.666666666666667, feat[3]))
assert abs(feat[3] - 0.666666666666667) < 0.00001, myMessage
request.setFilterFid(1)
feat = next(myVector.getFeatures(request))
myMessage = ('Expected: %f\nGot: %f\n' % (9.0, feat[1]))
assert feat[1] == 9.0, myMessage
myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2]))
assert feat[2] == 5.0, myMessage
myMessage = ('Expected: %f\nGot: %f\n' % (0.555555555555556, feat[3]))
assert abs(feat[3] - 0.555555555555556) < 0.00001, myMessage
request.setFilterFid(2)
feat = next(myVector.getFeatures(request))
myMessage = ('Expected: %f\nGot: %f\n' % (6.0, feat[1]))
assert feat[1] == 6.0, myMessage
myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2]))
assert feat[2] == 5.0, myMessage
myMessage = ('Expected: %f\nGot: %f\n' % (0.833333333333333, feat[3]))
assert abs(feat[3] - 0.833333333333333) < 0.00001, myMessage
示例8: testWriteShapefileWithMultiConversion
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testWriteShapefileWithMultiConversion(self):
"""Check writing geometries to an ESRI shapefile with conversion to multi."""
ml = QgsVectorLayer(
('Point?crs=epsg:4326&field=id:int'),
'test',
'memory')
assert ml is not None, 'Provider not initialized'
assert ml.isValid(), 'Source layer not valid'
provider = ml.dataProvider()
assert provider is not None
ft = QgsFeature()
ft.setGeometry(QgsGeometry.fromWkt('Point (1 2)'))
ft.setAttributes([1])
res, features = provider.addFeatures([ft])
assert res
assert len(features) > 0
dest_file_name = os.path.join(str(QDir.tempPath()), 'to_multi.shp')
print(dest_file_name)
crs = QgsCoordinateReferenceSystem()
crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
write_result = QgsVectorFileWriter.writeAsVectorFormat(
ml,
dest_file_name,
'utf-8',
crs,
'ESRI Shapefile',
forceMulti=True)
self.assertEqual(write_result, QgsVectorFileWriter.NoError)
# Open result and check
created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr')
f = created_layer.getFeatures(QgsFeatureRequest()).next()
g = f.geometry()
wkt = g.exportToWkt()
expWkt = 'MultiPoint ((1 2))'
assert compareWkt(expWkt, wkt), "saving geometry with multi conversion failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
示例9: writeShape
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def writeShape(theMemoryLayer, theFileName):
myFileName = os.path.join(str(QDir.tempPath()), theFileName)
print(myFileName)
# Explicitly giving all options, not really needed but nice for clarity
myErrorMessage = ''
myOptions = []
myLayerOptions = []
mySelectedOnlyFlag = False
mySkipAttributesFlag = False
myGeoCrs = QgsCoordinateReferenceSystem()
myGeoCrs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
myResult = QgsVectorFileWriter.writeAsVectorFormat(
theMemoryLayer,
myFileName,
'utf-8',
myGeoCrs,
'ESRI Shapefile',
mySelectedOnlyFlag,
myErrorMessage,
myOptions,
myLayerOptions,
mySkipAttributesFlag)
assert myResult == QgsVectorFileWriter.NoError
示例10: tearDown
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def tearDown(self):
report_file_path = "%s/qgistest.html" % QDir.tempPath()
with open(report_file_path, 'a') as report_file:
report_file.write(self.report)
示例11: testWriteShapefileWithZ
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testWriteShapefileWithZ(self):
"""Check writing geometries with Z dimension to an ESRI shapefile."""
#start by saving a memory layer and forcing z
ml = QgsVectorLayer(
('Point?crs=epsg:4326&field=id:int'),
'test',
'memory')
assert ml is not None, 'Provider not initialized'
assert ml.isValid(), 'Source layer not valid'
provider = ml.dataProvider()
assert provider is not None
ft = QgsFeature()
ft.setGeometry(QgsGeometry.fromWkt('PointZ (1 2 3)'))
ft.setAttributes([1])
res, features = provider.addFeatures([ft])
assert res
assert len(features) > 0
# check with both a standard PointZ and 25d style Point25D type
for t in [QgsWKBTypes.PointZ, QgsWKBTypes.Point25D]:
dest_file_name = os.path.join(str(QDir.tempPath()), 'point_{}.shp'.format(QgsWKBTypes.displayString(t)))
print(dest_file_name)
crs = QgsCoordinateReferenceSystem()
crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
write_result = QgsVectorFileWriter.writeAsVectorFormat(
ml,
dest_file_name,
'utf-8',
crs,
'ESRI Shapefile',
overrideGeometryType=t)
self.assertEqual(write_result, QgsVectorFileWriter.NoError)
# Open result and check
created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr')
f = created_layer.getFeatures(QgsFeatureRequest()).next()
g = f.geometry()
wkt = g.exportToWkt()
expWkt = 'PointZ (1 2 3)'
assert compareWkt(expWkt, wkt), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
#also try saving out the shapefile version again, as an extra test
#this tests that saving a layer with z WITHOUT explicitly telling the writer to keep z values,
#will stay retain the z values
dest_file_name = os.path.join(str(QDir.tempPath()), 'point_{}_copy.shp'.format(QgsWKBTypes.displayString(t)))
print(dest_file_name)
crs = QgsCoordinateReferenceSystem()
crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
write_result = QgsVectorFileWriter.writeAsVectorFormat(
created_layer,
dest_file_name,
'utf-8',
crs,
'ESRI Shapefile')
self.assertEqual(write_result, QgsVectorFileWriter.NoError)
# Open result and check
created_layer_from_shp = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr')
f = created_layer_from_shp.getFeatures(QgsFeatureRequest()).next()
g = f.geometry()
wkt = g.exportToWkt()
assert compareWkt(expWkt, wkt), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
示例12: testWriteShapefileWithAttributeSubsets
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def testWriteShapefileWithAttributeSubsets(self):
"""Tests writing subsets of attributes to files."""
ml = QgsVectorLayer(
('Point?crs=epsg:4326&field=id:int&field=field1:int&field=field2:int&field=field3:int'),
'test',
'memory')
assert ml is not None, 'Provider not initialized'
assert ml.isValid(), 'Source layer not valid'
provider = ml.dataProvider()
assert provider is not None
ft = QgsFeature()
ft.setGeometry(QgsGeometry.fromWkt('Point (1 2)'))
ft.setAttributes([1, 11, 12, 13])
res, features = provider.addFeatures([ft])
assert res
assert len(features) > 0
#first write out with all attributes
dest_file_name = os.path.join(str(QDir.tempPath()), 'all_attributes.shp')
crs = QgsCoordinateReferenceSystem()
crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
write_result = QgsVectorFileWriter.writeAsVectorFormat(
ml,
dest_file_name,
'utf-8',
crs,
'ESRI Shapefile',
attributes=[])
self.assertEqual(write_result, QgsVectorFileWriter.NoError)
# Open result and check
created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr')
self.assertEqual(created_layer.fields().count(), 4)
f = next(created_layer.getFeatures(QgsFeatureRequest()))
self.assertEqual(f['id'], 1)
self.assertEqual(f['field1'], 11)
self.assertEqual(f['field2'], 12)
self.assertEqual(f['field3'], 13)
#now test writing out only a subset of attributes
dest_file_name = os.path.join(str(QDir.tempPath()), 'subset_attributes.shp')
write_result = QgsVectorFileWriter.writeAsVectorFormat(
ml,
dest_file_name,
'utf-8',
crs,
'ESRI Shapefile',
attributes=[1, 3])
self.assertEqual(write_result, QgsVectorFileWriter.NoError)
# Open result and check
created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr')
self.assertEqual(created_layer.fields().count(), 2)
f = next(created_layer.getFeatures(QgsFeatureRequest()))
self.assertEqual(f['field1'], 11)
self.assertEqual(f['field3'], 13)
#finally test writing no attributes
dest_file_name = os.path.join(str(QDir.tempPath()), 'no_attributes.shp')
write_result = QgsVectorFileWriter.writeAsVectorFormat(
ml,
dest_file_name,
'utf-8',
crs,
'ESRI Shapefile',
skipAttributeCreation=True)
self.assertEqual(write_result, QgsVectorFileWriter.NoError)
# Open result and check
created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr')
# expect only a default 'FID' field for shapefiles
self.assertEqual(created_layer.fields().count(), 1)
self.assertEqual(created_layer.fields()[0].name(), 'FID')
# in this case we also check that the geometry exists, to make sure feature has been correctly written
# even without attributes
f = next(created_layer.getFeatures(QgsFeatureRequest()))
g = f.geometry()
wkt = g.exportToWkt()
expWkt = 'Point (1 2)'
assert compareWkt(expWkt, wkt), "geometry not saved correctly when saving without attributes : mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
self.assertEqual(f['FID'], 0)
示例13: tempFolder
# 需要导入模块: from PyQt.QtCore import QDir [as 别名]
# 或者: from PyQt.QtCore.QDir import tempPath [as 别名]
def tempFolder():
tempDir = os.path.join(unicode(QDir.tempPath()), 'processing' + _tempFolderSuffix)
if not QDir(tempDir).exists():
QDir().mkpath(tempDir)
return unicode(os.path.abspath(tempDir))