3

When I run this code in QGIS Python console it works fine, but I want want to run it from an external Python script.

What I want the script to do is: 1- Open QGIS 2- Run this code 3- Close QGIS

from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtXml import *

mapinstance = QgsMapLayerRegistry.instance()

uri =  "file:///C:/Users/Home/Desktop//sample.csv?delimiter=%s&xField=%s&yField=%s" % (",", "Long", "Lat") 

vlayer=QgsVectorLayer(uri,"sample","delimitedtext")
mapinstance.addMapLayer(vlayer)

uri="C:/Users/Home/Desktop/Style.qml"
vlayer.loadNamedStyle(uri)


vlayer.selectAll()
qgis.utils.iface.actionZoomToSelected().trigger()
vlayer.invertSelection ()

qgis.utils.iface.mapCanvas().saveAsImage('/Users/HOME/Desktop/capture.png')
3

You will want to run this as a standalone application. The reference for this can be found in the appropritate pyqgis cookbook section.

You need to run setup code at the beginning and cleanup code at the end.

# ...
# [ Your imports here ]
# ...

# supply path to where is your qgis installed
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)

# load providers
QgsApplication.initQgis()

# ...
# [ Your code here ]
# ...

canvas = QgsMapCanvas()
canvas.setLayerSet([QgsMapCanvasLayer(layer)])
canvas.zoomToFullExtent()

canvas.saveAsImage('/Users/HOME/Desktop/capture.png')

QgsApplication.exitQgis()
4
  • when I try to run the .py script with the OSGeo4W Shell but nothing happens. when I try to open it with the standalone python installation, it give me an error "ImportError: No module named sip" – amamdouh Jun 5 '14 at 12:00
  • What do you mean by "noting happens"? The OSGeo4W python is surely the right thing to use, as that's what QGIS builds upon. – Matthias Kuhn Jun 5 '14 at 13:05
  • It doesn't accept this line of the code "qgis.utils.iface.actionZoomToSelected().trigger()" and also, how can I make the OSGEO4W the default python interpreter. Thank you. – amamdouh Jun 5 '14 at 16:47
  • iface is not available. So instead you will have to use some custom code to bring things up and running... Updating the example... – Matthias Kuhn Jun 5 '14 at 22:42

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.