You can run a QGIS Processing algorithm in standalone (no GUI) mode in this way:
from qgis.core import (
# See https://gis.stackexchange.com/a/155852/4972 for details about the prefix
qgs = QgsApplication(, False)
Finally found the proper way of running processing algorithms in PyQGIS standalone scripts.
This answer is based on answers to Problem with import qgis.core when writing a stand-alone PyQGIS script and to Error: Algorithm not found, which is in turn based on a Qgis-dev mailing-list discussion.
I suggest you to follow the work flow given in Problem with ...
In order to solve this question, we need to use timers or something that delays the execution of the script, so the canvas can reflect the layer arrangement at the time the map is exported. In other words, if you don't use timers you'll end up with 3 PNG images with the same content because everything will happen too fast.
In the QGIS map, set the map ...
I think Nathan W's answer is out of date. I was able to run QGIS (version 2.6) python scripts from the command line (Nathan's option 4) using the following commands.
qgis -nologo --project /path/foo.qgs --code /path/foo.py
To complement Luigi's answer, this is how you can use the Layer Tree View for adding a legend (also known as Table of Contents or ToC) to your application.
After you create your canvas in your standalone PyQGIS application, you need to create a QgsLayerTreeView. For that, you need a model, and for the model you need the layer tree root. Additionally, you ...
To avoid "layer is not valid" errors you should carefully set your QGIS prefix path. The prefix path must be set to let QGIS know where to find resources such as data providers and the reference system database. If you look at your QGIS installation, you should be able to access lib/qgis/plugins on Unix (or just plugins on Windows), relative to the ...
Yes - processing.run accepts a "feedback" argument, which must be an instance of a QgsProcessingFeedback subclass.
If you construct your own feedback object to pass to this function, you can connect to the progressChanged signal and handle progress reports:
f = QgsProcessingFeedback()
On the one hand, QgsMapCanvas is a class. You can always create new canvas objects from it (as you did already in your second attempt).
On the other hand, iface.mapCanvas() is an instance, an object of the class QgsMapCanvas. iface.mapCanvas() is initialized when you load QGIS app with GUI (Python should be enabled to use it), and refers to the main canvas ...
Being very keen on the TDD paradigm, I've spent some time putting together a dummy-interface (based on some code fragments I found on the internet) which enables calling QGIS and QGIS-plugins standalone.
The interface I came up with looks as follows and I used it for all my unit-tests since:
"""QGIS plugin implementation.
.. note:: This ...
yes, see for example:
GRASS and Python
On scripting GRASS GIS: Building location-independent command line tools
Python Scripts For GRASS GIS
Using Python scripts that call GRASS modules or access GRASS layers from outside the GRASS.app with Mac OS X: a little summary
How to access vector coordinates in GRASS GIS from python?
Update for Nathan's option 4: (Windows, QGIS 2.18 Las Palmas)
To print QGIS help document,
To open QGIS, load a project, then, run a python script.
qgis --nologo --project c:/path/to/projfile.qgs --code c:/path/to/code.py
These commands should run on OSGeo4W Shell without problems.
QGIS 3.18 also works.
Always use this command to see all ...
This answer is based on answers to Problem with import qgis.core when writing a stand-alone PyQGIS script and to How can I access `processing` with Python?.
I suggest you to follow the work flow given in Problem with import qgis.core when writing a stand-alone PyQGIS script to enable your QGIS libraries in your OSGeo4W Shell. Once you have your QGIS ...
If you keep getting non valid layers, even defining them correctly, you're probably missing the QGIS prefix definition in your script (in case that you work out of QGIS).
If you work on Windows, your qgis_prefix should be something like this:
Add two following lines before qp = QgsProject.instance():
qgs = QgsApplication(, False)
then, add the next line to the end of the script:
An additional warning: You should convert ImageExportSettings() into PdfExportSettings() since you export the layout to pdf. Otherwise, you will get this error:
This code works in my Python Console:
from qgis.core import QgsRasterLayer
from PyQt4.QtCore import QFileInfo
# Check if string is provided
fileInfo = QFileInfo(raster)
path = fileInfo.filePath()
baseName = fileInfo.baseName()
layer = QgsRasterLayer(path, baseName)
When you intend to run PyQGIS scripts out of QGIS, you need to initialize a QgsApplication so that it loads data providers and other resources. The following code snippet should work:
from qgis.core import *
from PyQt4.QtGui import QApplication
app = QApplication()
QgsApplication.setPrefixPath("C:\\OSGeo4W\\apps\\qgis\\", True) # Adjust prefix path ...
symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
renderer = QgsSingleSymbolRendererV2(symbol)
Now you have 10 types of fill:
Simple fill, QgsSimpleFillSymbolLayerV2
Gradient fill, QgsGradientFillSymbolLayerV2
Centroid fill, QgsCentroidFillSymbolLayerV2
Line pattern fill, QgsLinePatternFillSymbolLayer
Point pattern fill, ...
When defining a new memory layer, you need to include one of the following as the data source:
Point - For a point layer.
LineString - For a line layer.
Polygon - For a polygon layer.
So in your case, you should replace:
mem_layer = QgsVectorLayer("Lines?crs=epsg:4326&index=yes", "duplicated_layer", "memory")
mem_layer = QgsVectorLayer("...
The following script generates a simple form. You can use it in your standalone PyQGIS application to display attributes for a given feature. You can also specify fields to be displayed (or not to be displayed).
from qgis.PyQt.QtWidgets import *
def __init__(self, layer, feature, only=None, exclude=None): ...
Non-valid layers are most of the times due to a wrong QGIS prefix definition.
Please try with:
qgis_prefix="C:\\Program Files\\QGIS Wiena\\apps\\qgis"
Which should go right before this line:
Now your tested layers should be valid.
Based on this Very old help you want to use your IStandaloneTableCollection
IStandaloneTableCollection pColl = ArcMap.Document.FocusMap as IStandaloneTableCollection;
IStandaloneTable pThisTable = pColl.StandaloneTable; // the first table
ArcMap.Document.UpdateContents(); //update ...
I tested your code and stripped the problem down to the paths you are using. The error seems to be the forward slashes (/) that confuse your windows python installation. You should use backslashes on windows and use them as escaped symbol (eg. double backslash \). I updated your code with the paths of my system (an OSGeo4W64 installation), you can change ...
My GDAL_DATA environment variable was wrong, it had a line break (\n) at the end causing my error. I fixed it by forcefully changing the environment variable to remove the line break.
QgsApplication.instance().initQgis() appears to add line breaks to the end of all my environment paths. I have patched this by replacing the line break in each variable ...
To use native algorithms in a standalone application, you need to add the provider using:
It would be like this:
from qgis.analysis import QgsNativeAlgorithms
from processing.core.Processing import Processing
You can execute the following code in the Python Console of QGIS.
from PyQt5.QtCore import QVariant
# Step 1 : Adding the Area field
layer = QgsVectorLayer("C:/Users/ja/Inne/Desktop/treningowawarstwa.shp", "your_layer", "ogr")
provider = layer.dataProvider()
area_field = QgsField("Area", QVariant.Int)
To copy all contents of a plugin folder to QGIS plugins folder, you can use a batch script below (see code comments starting with rem). What the script does in short is to copy contents of the plugin folder from a path to the QGIS plugin path. However, if the folder already exists, it overwrites it.
This should be enough to get the extent of your Shapefile:
layerPath = path_dir + "Input district shapefile\\" + "District.shp"
extent = QgsVectorLayer( layerPath, '', 'ogr' ).extent()
The result is a QgsRectangle object, which has xMinimum(), xMaximum(), yMinimum(), and yMaximum() methods.
Struggled a bit for last 2 days. Abandoned XML approach. Able to accomplish first 2 tasks.
Need to check how I can accomplish setting WFS,WCS parameters
Create .qgs file dynamically
Add Legend and Layers to the .qgs file and save
Set WFS,WCS parameters in the .qgs file
from xml.dom.minidom import Document
I had to make minor changes to the script provided by @gcarrillo to include the OSGEO4W64 path (I had to re-install QGIS via the OSGEO4W64 installer as I used the standalone installer initially) and to include double-slashes. Here is the final script and many thanks to everyone for their help:
import os, sys, glob
# Prepare the environment
from qgis.core ...