本文整理汇总了Python中PyQt.QtCore.QDir类的典型用法代码示例。如果您正苦于以下问题:Python QDir类的具体用法?Python QDir怎么用?Python QDir使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QDir类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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
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: testQgsSvgMarkerSymbolLayerV2
def testQgsSvgMarkerSymbolLayerV2(self):
"""
Create a new style from a .sld file and match test
"""
mTestName = 'QgsSvgMarkerSymbolLayerV2'
mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))
mDoc = QDomDocument(mTestName)
mFile = QFile(mFilePath)
mFile.open(QIODevice.ReadOnly)
mDoc.setContent(mFile, True)
mFile.close()
mSymbolLayer = QgsSvgMarkerSymbolLayerV2.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())
mExpectedValue = type(QgsSvgMarkerSymbolLayerV2())
mValue = type(mSymbolLayer)
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = u'skull.svg'
mValue = os.path.basename(mSymbolLayer.path())
print("VALUE", mSymbolLayer.path())
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = 12
mValue = mSymbolLayer.size()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = 45
mValue = mSymbolLayer.angle()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
示例4: testQgsSVGFillSymbolLayer
def testQgsSVGFillSymbolLayer(self):
"""
Create a new style from a .sld file and match test
"""
mTestName = 'QgsSVGFillSymbolLayer'
mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))
mDoc = QDomDocument(mTestName)
mFile = QFile(mFilePath)
mFile.open(QIODevice.ReadOnly)
mDoc.setContent(mFile, True)
mFile.close()
mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld(
mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())
mExpectedValue = type(QgsSVGFillSymbolLayer())
mValue = type(mSymbolLayer)
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = 'accommodation_camping.svg'
mValue = os.path.basename(mSymbolLayer.svgFilePath())
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = 6
mValue = mSymbolLayer.patternWidth()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
示例5: testQgsCentroidFillSymbolLayerV2
def testQgsCentroidFillSymbolLayerV2(self):
"""
Create a new style from a .sld file and match test
"""
mTestName = 'QgsCentroidFillSymbolLayerV2'
mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))
mDoc = QDomDocument(mTestName)
mFile = QFile(mFilePath)
mFile.open(QIODevice.ReadOnly)
mDoc.setContent(mFile, True)
mFile.close()
mSymbolLayer = QgsCentroidFillSymbolLayerV2.createFromSld(
mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())
mExpectedValue = type(QgsCentroidFillSymbolLayerV2())
mValue = type(mSymbolLayer)
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = u'regular_star'
mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = u'#55aaff'
mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = u'#00ff00'
mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
示例6: saveAsScriptFile
def saveAsScriptFile(self, index=None):
tabWidget = self.tabEditorWidget.currentWidget()
if not index:
index = self.tabEditorWidget.currentIndex()
if not tabWidget.path:
fileName = self.tabEditorWidget.tabText(index) + '.py'
folder = self.settings.value("pythonConsole/lastDirPath", QDir.home())
pathFileName = os.path.join(folder, fileName)
fileNone = True
else:
pathFileName = tabWidget.path
fileNone = False
saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As")
filename = QFileDialog.getSaveFileName(self,
saveAsFileTr,
pathFileName, "Script file (*.py)")
if filename:
try:
tabWidget.save(filename)
except (IOError, OSError) as error:
msgText = QCoreApplication.translate('PythonConsole',
'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
error.strerror)
self.callWidgetMessageBarEditor(msgText, 2, False)
if fileNone:
tabWidget.path = None
else:
tabWidget.path = pathFileName
return
if not fileNone:
self.updateTabListScript(pathFileName, action='remove')
示例7: testDateTimeWriteShapefile
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"))
示例8: testStatistics
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
示例9: testPrintMapFromTemplate
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
示例10: batchRun
def batchRun(self):
exts = re.sub('\).*$', '', re.sub('^.*\(', '', self.formatCombo.currentText())).split(" ")
if len(exts) > 0 and exts[0] != "*" and exts[0] != "*.*":
outExt = exts[0].replace("*", "")
else:
outExt = ".tif"
self.base.enableRun(False)
self.base.setCursor(Qt.WaitCursor)
inDir = self.getInputFileName()
outDir = self.getOutputFileName()
extensions = Utils.getRasterExtensions()
workDir = QDir(inDir)
workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot)
workDir.setNameFilters(extensions)
files = workDir.entryList()
self.inFiles = []
self.outFiles = []
for f in files:
self.inFiles.append(inDir + "/" + f)
if outDir is not None:
outFile = re.sub("\.[a-zA-Z0-9]{2,4}", outExt, f)
self.outFiles.append(outDir + "/" + outFile)
self.errors = []
self.batchIndex = 0
self.batchTotal = len(self.inFiles)
self.setProgressRange(self.batchTotal)
self.runItem(self.batchIndex, self.batchTotal)
示例11: imageCheck
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
示例12: testWrite
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"
示例13: requestFinished
def requestFinished(self):
reply = self.sender()
self.buttonBox.setEnabled(False)
if reply.error() != QNetworkReply.NoError:
self.mResult = reply.errorString()
if reply.error() == QNetworkReply.OperationCanceledError:
self.mResult += "<br/><br/>" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options.")
self.reject()
reply.deleteLater()
return
self.file.open(QFile.WriteOnly)
self.file.write(reply.readAll())
self.file.close()
self.stateChanged(0)
reply.deleteLater()
pluginDir = qgis.utils.home_plugin_path
tmpPath = self.file.fileName()
# make sure that the parent directory exists
if not QDir(pluginDir).exists():
QDir().mkpath(pluginDir)
# if the target directory already exists as a link, remove the link without resolving:
QFile(pluginDir + unicode(QDir.separator()) + self.plugin["id"]).remove()
try:
unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs
# removing old plugin files if exist
removeDir(QDir.cleanPath(pluginDir + "/" + self.plugin["id"])) # remove old plugin if exists
unzip(unicode(tmpPath), unicode(pluginDir)) # final extract.
except:
self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir
self.reject()
return
try:
# cleaning: removing the temporary zip file
QFile(tmpPath).remove()
except:
pass
self.close()
示例14: testQgsSimpleLineSymbolLayerV2
def testQgsSimpleLineSymbolLayerV2(self):
"""
Create a new style from a .sld file and match test
"""
mTestName = 'QgsSimpleLineSymbolLayerV2'
mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))
mDoc = QDomDocument(mTestName)
mFile = QFile(mFilePath)
mFile.open(QIODevice.ReadOnly)
mDoc.setContent(mFile, True)
mFile.close()
mSymbolLayer = QgsSimpleLineSymbolLayerV2.createFromSld(
mDoc.elementsByTagName('LineSymbolizer').item(0).toElement())
mExpectedValue = type(QgsSimpleLineSymbolLayerV2())
mValue = type(mSymbolLayer)
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = u'#aa007f'
mValue = mSymbolLayer.color().name()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = 1.26
mValue = mSymbolLayer.width()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = Qt.RoundCap
mValue = mSymbolLayer.penCapStyle()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = Qt.MiterJoin
mValue = mSymbolLayer.penJoinStyle()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = True
mValue = mSymbolLayer.useCustomDashPattern()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
mExpectedValue = [5.0, 2.0]
mValue = mSymbolLayer.customDashVector()
mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
assert mExpectedValue == mValue, mMessage
示例15: getAllInstalled
def getAllInstalled(self, testLoad=True):
""" Build the localCache """
self.localCache = {}
# reversed list of the plugin paths: first system plugins -> then user plugins -> finally custom path(s)
pluginPaths = list(plugin_paths)
pluginPaths.reverse()
for pluginsPath in pluginPaths:
isTheSystemDir = (pluginPaths.index(pluginsPath) == 0) # The curent dir is the system plugins dir
if isTheSystemDir:
# temporarily add the system path as the first element to force loading the readonly plugins, even if masked by user ones.
sys.path = [pluginsPath] + sys.path
try:
pluginDir = QDir(pluginsPath)
pluginDir.setFilter(QDir.AllDirs)
for key in pluginDir.entryList():
if key not in [".", ".."]:
path = QDir.convertSeparators(pluginsPath + "/" + key)
# readOnly = not QFileInfo(pluginsPath).isWritable() # On windows testing the writable status isn't reliable.
readOnly = isTheSystemDir # Assume only the system plugins are not writable.
# only test those not yet loaded. Loaded plugins already proved they're o.k.
# failedToLoad = settings.value("/PythonPlugins/watchDog/" + key) is not None
testLoadThis = testLoad and key not in qgis.utils.plugins
plugin = self.getInstalledPlugin(key, path=path, readOnly=readOnly, testLoad=testLoadThis)
self.localCache[key] = plugin
if key in self.localCache.keys() and compareVersions(self.localCache[key]["version_installed"], plugin["version_installed"]) == 1:
# An obsolete plugin in the "user" location is masking a newer one in the "system" location!
self.obsoletePlugins += [key]
except:
# it's not necessary to stop if one of the dirs is inaccessible
pass
if isTheSystemDir:
# remove the temporarily added path
sys.path.remove(pluginsPath)