Monday 30 April 2018

qgis - Accessing `processing` with Python?


I want to access the explode lines function in Python outside of QGIS from a standalone script.



What module do I have to load in order to use it?


How can I access processing?


from qgis.core import *

layerInput = QgsVectorLayer('test.shp', 'test', 'ogr')

processing.runalg('qgis:explodelines', layerInput, 'temp.shp')

Answer



UPDATE 24.04.2018: See how to do this in QGIS v3.x here.





For QGIS v2.x


Finally found the proper way of running processing algorithms via standalone PyQGIS scripts.


Using Processing plugin version 2.2.0-2, you can try the following script:


# Prepare the environment
import sys
from qgis.core import *
from PyQt4.QtGui import *
app = QApplication([])
QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()


# Prepare processing framework
sys.path.append('/home/user/.qgis2/python/plugins') # Folder where Processing is located
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *

# Run the algorithm
layerInput = QgsVectorLayer('test.shp', 'test', 'ogr')
general.runalg('qgis:explodelines', layerInput, 'temp.shp')


# Exit applications
QgsApplication.exitQgis()
QApplication.exit()

Newer Processing versions could be located at /usr/share/qgis/python/plugins, so you might need to use sys.path.append('/usr/share/qgis/python/plugins') accordingly.


I found the working example in Error: Algorithm not found, which is in turn based on a Qgis-dev mailing-list discussion.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...