Calculating line lengths using PyQGIS
From the QGIS Documents: Geometry Handling, you can use the following code to get the length of any selected line(s):
layer = qgis.utils.iface.activeLayer()
features = layer.selectedFeatures()
for f in features:
geom = f.geometry()
print "Length:", geom.length()
Great code, however, this only works for the selected layer and only prints it. With some help from other posts and @Joseph I turned it into a code that adds an attribute to all layers in your project with the length.
from PyQt4.QtCore import QVariant
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
features = layer.getFeatures()
for f in features:
geom = f.geometry()
leng = geom.length()
res = layer.dataProvider().addAttributes([QgsField("Length", QVariant.Int)])
layer.updateFields()
fieldIndex = layer.dataProvider().fieldNameIndex("Length")
attrFeatMap = {}
attrMap = {fieldIndex: leng}
for feature in layer.getFeatures():
attrFeatMap[feature.id()] = attrMap
layer.dataProvider().changeAttributeValues(attrFeatMap)