Stand-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
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() # Add the path to processing so we can import it next sys.path.append(r'C:\OSGeo4W64\apps\qgis-dev\python\plugins') # Imports usually should be at the top of a script but this unconventional # order is necessary here because QGIS has to be initialized first 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)