You need to create a batch file to bootstrap your Python file that setups the correct environment. This is the one I use for all of my standalone QGIS apps:
REM Change OSGEO4W_ROOT to point to the base install folder
SET OSGEO4W_ROOT=C:\OSGeo4W
SET QGISNAME=qgis
SET QGIS=%OSGEO4W_ROOT%\apps\%QGISNAME%
set QGIS_PREFIX_PATH=%QGIS%
REM Python Setup
set PATH=%OSGEO4W_ROOT%\bin;%QGIS%\bin;%PATH%
SET PYTHONHOME=%OSGEO4W_ROOT%\apps\Python27
set PYTHONPATH=%QGIS%\python;%PYTHONPATH%
python yourscript.py
The QGISNAME
variable is only so I can swap between release qgis and dev QGIS for testing, remove if not needed.
Your PYTHONHOME should be:
C:\OSGeo4W64\apps\Python27
Your PATH should include (in the beggining):
C:\OSGeo4W64\bin; C:\OSGeo4W64\apps\qgis\bin
PYTHONPATH should have:
C:\OSGeo4W64\apps\qgis\python
C:\OSGeo4W64\apps\qgis\python\plugins
C:\OSGeo4W64\bin\python27.zip
C:\OSGeo4W64\apps\Python27\DLLs
C:\OSGeo4W64\apps\Python27
C:\OSGeo4W64\apps\Python27\lib
C:\OSGeo4W64\apps\Python27\lib\site-packages
In code you have to:
import sys
from qgis.core import QgsApplication
QgsApplication.setPrefixPath('C:\OSGeo4W64\apps\qgis', True)
qgs = QgsApplication(sys.argv, False)
qgs.initQgis()
If you don't have sip in your Python installation you should install it.
EDIT
Provided you are running the correct python version for pyqgis you can setup everything in python code:
import sys, os
os.environ['PATH'] = 'C:\\OSGeo4W64\\apps\\qgis\\bin;C:\\OSGeo4W64\\bin;' + os.environ['PATH']
sys.path.extend(['C:\\OSGeo4W64\\apps\\qgis\\python', 'C:\\OSGeo4W64\\apps\\qgis\\python\\plugins', 'C:\\OSGeo4W64\\bin\\python27.zip', 'C:\\OSGeo4W64\\apps\\Python27\\DLLs', 'C:\\OSGeo4W64\\apps\\Python27', 'C:\\OSGeo4W64\\apps\\Python27\\lib', 'C:\\OSGeo4W64\\apps\\Python27\\lib\\site-packages'])
Best Answer
if you use the Kyng Chaos version:
1) First solution with the PYTHONPATH variable:
Add qgis to the PYTHONPATH (terminal)
You can add this line to your .bash_profile
Then in Python
Then you can use PyQGIS
2) second solution, all in Python (from Custom Initialization for running standalone PyQGIS processing.):
If you use the Homebrew version , the PATHs are different (look at Homebrew-osgeo4mac)