tand-alone PyQGIS scripts with OSGeo4W
PyQGIS scripts are great to automate spatial processing workflows. It’s easy to run these scripts inside QGIS but it can be even more convenient to run PyQGIS scripts without even having to launch QGIS. To create a so-called “stand-alone” PyQGIS script, there are a few things that need to be taken care of. The following steps show how to set up PyCharm for stand-alone PyQGIS development on Windows10 with OSGeo4W.
An essential first step is to ensure that all environment variables are set correctly. The most reliable approach is to go to C:\OSGeo4W64\bin (or wherever OSGeo4W is installed on your machine), make a copy of qgis-dev-g7.bat (or any other QGIS version that you have installed) and rename it to pycharm.bat:
Instead of launching QGIS, we want that pycharm.bat launches PyCharm. Therefore, we edit the final line in the .bat file to start pycharm64.exe:
In PyCharm itself, the main task to finish our setup is configuring the project interpreter:
First, we add a new “system interpreter” for Python 3.7 using the corresponding OSGeo4W Python installation.
To finish the interpreter config, we need to add two additional paths pointing to QGIS\python and QGIS\python\plugins:
That’s it! Now we can start developing our stand-alone PyQGIS script.
The following example shows the necessary steps, particularly:
Initializing QGIS
Initializing Processing
Running a Processing algorithm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import sys
from qgis.core import QgsApplication, QgsProcessingFeedback
from qgis.analysis import QgsNativeAlgorithms
QgsApplication.setPrefixPath(r'C:\OSGeo4W64\apps\qgis-dev', True)
qgs = QgsApplication([], False)
qgs.initQgis()
sys.path.append(r'C:\OSGeo4W64\apps\qgis-dev\python\plugins')
import processing
from processing.core.Processing import Processing
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
feedback = QgsProcessingFeedback()
rivers = r'D:\Documents\Geodata\NaturalEarthData\Natural_Earth_quick_start\10m_physical\ne_10m_rivers_lake_centerlines.shp'
output = r'D:\Documents\Geodata\temp\danube3.shp'
expression = "name LIKE '%Danube%'"
danube = processing.run(
'native:extractbyexpression',
{'INPUT': rivers, 'EXPRESSION': expression, 'OUTPUT': output},
feedback=feedback
)['OUTPUT']
print(danube)
<div class="open_grepper_editor" title="Edit & Save To Grepper"></div>