2

I have a python script that runs in QGIS that I would like to run without opening QGIS. The script is as follows:

QGIS_Zonal_Stats_osGeo.py

import sys
from qgis.core import *

QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
app = QgsApplication([], True)
QgsApplication.initQgis()

sys.path.append("C:/OSGeo4W64/apps/qgis/python/plugins")

from processing.core.Processing import Processing
Processing.initialize()
import processing

from qgis.analysis import QgsZonalStatistics

import datetime

today = datetime.date.today()
one_day = datetime.timedelta(days=1)
yesterday = today - one_day
yesterday_date = yesterday.strftime('"%Y-%m-%d"').lstrip("0").replace(" 0", " ")
yesterday_date_name = yesterday.strftime("%B_%d_%Y").lstrip("0").replace(" 0", " ")

rasterFilePath = 'C:/Users/bboyko/Desktop/precipitation_download/Daily_Rainfall/' + str(yesterday_date_name) + '.tif'

polygonLayer = QgsVectorLayer('C:/Users/bboyko/Desktop/precipitation_download/candidate_singlepart.shp', 
'candidate_singlepart', "ogr") 

rasterLayer = QgsRasterLayer(rasterFilePath, str(yesterday_date_name))

zoneStat = QgsZonalStatistics (polygonLayer, rasterLayer, 'rain_', 1, QgsZonalStatistics.Mean)

zoneStat.calculateStatistics(None)

And this is the .bat file I am using:

Launch.bat

SET QGIS=C:\OSGeo4W64\apps\qgis
SET PATH=C:\OSGeo4W64\bin;C:\OSGeo4W64\apps\qgis\bin;%PATH%
SET PYTHONHOME=C:\OSGeo4W64\apps\Python37
SET PYTHONPATH=C:\OSGeo4W64\apps\qgis\python;%PYTHONPATH%

python C:\Users\bboyko\Desktop\precipitation_download\QGIS_Zonal_Stats_Three_osGeo.py
pause

When I run the batch file this is the message I receive in a command prompt:

C:\Users\bboyko\Desktop\precipitation_download>python C:\Users\bboyko\Desktop\precipitation_download\QGIS_Zonal_Stats_Three_osGeo.py
  File "C:\OSGeo4W64\apps\Python37\lib\site.py", line 177
    file=sys.stderr)
        ^
SyntaxError: invalid syntax

Is the mistake coming from my python script or my .bat file, of from some other issue I haven't considered.

1

Change your Launch.bat for something like this:

@ECHO OFF 

set OSGEO4W_ROOT=C:\OSGeo4W64

@echo off
call "%OSGEO4W_ROOT%\bin\o4w_env.bat"
call "%OSGEO4W_ROOT%\bin\qt5_env.bat"
call "%OSGEO4W_ROOT%\bin\py3_env.bat"

@echo off
path %OSGEO4W_ROOT%\apps\qgis\bin;%PATH%
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT:\=/%/apps/qgis
set GDAL_FILENAME_IS_UTF8=YES

set VSI_CACHE=TRUE
set VSI_CACHE_SIZE=1000000
set QT_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\qgis\qtplugins;%OSGEO4W_ROOT%\apps\qt5\plugins
set PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis\python;%PYTHONPATH%

python C:\Users\bboyko\Desktop\precipitation_download\QGIS_Zonal_Stats_Three_osGeo.py
pause

It should work

Not the answer you're looking for? Browse other questions tagged or ask your own question.