1

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

CRS=QgsCoordinateReferenceSystem().fromEpsgId(4326)
error = QgsVectorFileWriter.writeAsVectorFormat(vl,fp, "system", CRS, "ESRI Shapefile")
if QgsVectorFileWriter.hasError(error):
    print("uh oh an error")
    print(QgsVectorFileWriter.errorMessage(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?

1 Answer 1

6

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))
2
  • 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
    Commented Feb 21, 2019 at 11:21
  • If I run this line: writer = QgsVectorFileWriter.writeAsVectorFormat(arguments etc..), my returned writer tuple is (8, ''). In other words, a blank error string. How do I use that?
    – grego
    Commented Mar 11, 2021 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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