PyQGIS – Script Not Running with Processing Import in QGIS 3.0

osgeopyqgisqgis-3qgis-processingstandalone

I have problems using version 3 of QGIS with Python 3. I followed different tutorials like this one :
how to use pyqgis processing runalg clipvectorsbypolygon

But it seems to be working only with QGIS 2.XX and not 3.0. Here is what I try to run :

from qgis.core import *
import PyQt5.QtCore

import sys
sys.path.append('C:/QGIS 3.0/apps/qgis/python/plugins')

qgs = QgsApplication([], True)
qgs.setPrefixPath("C:/QGIS 3.0/apps/qgis", True)
qgs.initQgis()

import processing

qgs.exitQgis()

But I get on PyCharm the error message : "Process finished with exit code 1".
I don't understand what is missing in my code. Can you please explain me how to use processing library with independent pyqgis scripts ?

Best Answer

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 them to match your directory structure:

from qgis.core import *
import PyQt5.QtCore

import sys

qgs = QgsApplication([], True)
qgs.setPrefixPath("C:\\OSGeo4W64\\apps\\qgis", True) 
#should be C:\\QGIS 3.0\\apps\\qgis

qgs.initQgis()

sys.path.append('C:\\OSGeo4W64\\apps\\qgis\\python\\plugins')
# should be "C:\\QGIS 3.0\\apps\\qgis\\python\\plugins" in your system

import processing


qgs.exitQgis()

Now the script should work. Sidenote: I ran the script from OSGeo4W Shell using the python-qgis command (python interpreter with QGIS paths). In case PyCharm still throws some errors, try running your script there or in PyDev (Eclipse). For reference: There is a similar answer to this one that also shows how to call native c++ algorithms from python.