Upgraded to QGIS 3.0 and now I cant read writer errors. The following (post 2to3) code doesnt print the error to the console:

error = QgsVectorFileWriter.writeAsVectorFormat(vl,fp, "system", CRS, "ESRI Shapefile")
if QgsVectorFileWriter.hasError(error):
    print("uh oh an error")

rather than reporting the error I get:

TypeError: QgsVectorFileWriter.hasError(): first argument of unbound method must have type 'QgsVectorFileWriter'

How can I modify this so that the write error is reported?


Have a look at the API Documentation which mentions the following signature for this method:

writeAsVectorFormat(layer: QgsVectorLayer, fileName: str, fileEncoding: str, destCRS: QgsCoordinateReferenceSystem = QgsCoordinateReferenceSystem(), driverName: str = '', onlySelected: bool = False, datasourceOptions: Iterable[str] = [], layerOptions: Iterable[str] = [], skipAttributeCreation: bool = False, newFilename: str = '', symbologyExport: QgsVectorFileWriter.SymbologyExport = QgsVectorFileWriter.NoSymbology, symbologyScale: float = 1, filterExtent: QgsRectangle = None, overrideGeometryType: QgsWkbTypes.Type = QgsWkbTypes.Unknown, forceMulti: bool = False, includeZ: bool = False, attributes: Iterable[int] = [], fieldValueConverter: QgsVectorFileWriter.FieldValueConverter = None) → Tuple[QgsVectorFileWriter.WriterError, str]

The last part is interesting here, it's the return value: → Tuple[QgsVectorFileWriter.WriterError, str]

Tuples can be read like this:

error, error_string = QgsVectorFileWriter.writeAsVectorFormat(....)

so you probably want to use something like this

error, error_string = QgsVectorFileWriter.writeAsVectorFormat(....)
if error != QgsVectorFileWriter.NoError:
    print('Oh an error has happened: {details}'.format(details=error_string))
  • Nice, here's hoping that tuple info makes it into the pyqgis cookbook which is still very much about 2.x. For some of us the api docs are rather opaque and a solid working example is a much faster way forward. Cheers. – Mr Purple Feb 21 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.