4

I have a Python script that runs in the QGIS Python console but I would like to run it outside of the console, so that a map can be created without having to be within QGIS. The script runs perfectly inside in the console but I just need to find a way how to use it from the outside, so I can then eventually use task scheduler to repeat this process at set time intervals. What are the steps I need to take in order for my script to run outside? I vaguely know that I need import modules/libraries that I have used into Python but I am unsure on how to do this and what other steps I need to take. I have looked at this hand book but I can't seem to find a way what to do - http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html. I have included an example of a small section of my script but included all imports:

import math
import json
import os
import glob
from qgis.PyQt import QtGui

#Add Base Map
urlWithParams = 'type=xyz&url=https://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857'
rlayer2 = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'wms')  

if rlayer2.isValid():
        QgsProject.instance().addMapLayer(rlayer2)
else:
        print('invalid layer')

#Add Vector Layers
vlayer = iface.addVectorLayer(latest_file, "Earthquake Event", "ogr")
if not vlayer:
    print("Layer failed to load!")
   
# Creating the distance buffers
layer = iface.activeLayer()
feats = [ feat for feat in layer.getFeatures() ]
epsg = layer.crs().postgisSrid()
uri = "Polygon?crs=epsg:" + str(epsg) + "&field=id:integer&field=x:real&    field=y:real&field=point_id:integer""&index=yes"

    #Using zonal statistics to work out affected population sum column 
    #######
    # there is no need to look for the raster layer again since you already saved it to a variable before(line 53)   
    prefix = rlayer.name()
    params = {'INPUT_RASTER': rlayer.name(), 'RASTER_BAND': 1, 'INPUT_VECTOR': f'MMI {intensity} Buffer', 'COLUMN_PREFIX': prefix+'_', 'STATS': 1}
    processing.run("qgis:zonalstatistics", params)



#This adds a map item to the Print Layout
map = QgsLayoutItemMap(layout)
map.setRect(20, 20, 20, 20)

#Choosing export folder and exporting layout
data_dir = os.path.join(os.path.expanduser('~'), 'Path_to_output')

output_file = feat['id'] + ' Event.png'
output_path = os.path.join(data_dir, output_file)

exporter = QgsLayoutExporter(layout)
exporter.exportToImage(
    output_path, QgsLayoutExporter.ImageExportSettings())

print("Finished")
9
  • 5
  • 1
    Please provide just a code snippet that illustrates what you want to do rather than your whole script.
    – PolyGeo
    Dec 15, 2020 at 11:43
  • Just changed it now so that only sections of my script is shown. Just didnt know if you needed the whole script to see what modules to add or not.
    – LiamHems
    Dec 15, 2020 at 11:47
  • @PolyGeo I have looked at the link and have made a new script. I just want to make sure I have done it correctly. The first line is - from qgis.core import *. Then I have put the path to the qgis installation. Then, the line after that is qgs = QgsApplication([], True), as I am using the GUI in my script. The line after is qgs.initQgis() and then my full script copied and pasted on the lines below that. Finally, qgs.exitQgis() is the last line.
    – LiamHems
    Dec 15, 2020 at 12:03
  • 2
    check this gis.stackexchange.com/a/289964/49538
    – Fran Raga
    Dec 17, 2020 at 12:49

1 Answer 1

3
+25

If python script runs perfectly, create an individual .py file and paste your code in it. Then save it. Make sure that you've set environment variable's PATH correctly. Finally create a .bat file like this:

ECHO OFF
cd \path\to\python\file
\path\to\python\installation\directory\python.exe <file_name>.py
PAUSE
7
  • The problem is that it works perfectly within the QGIS python console but when I come to use PyCharm to check if the script runs outside of the console, it does not seem to recognise the qgis module and therefore cannot define elements within QGIS such as QgsRasterLayer or QgsVectorLayer etc? Is there a way I can import the qgis module into pycharm, so it recognises these QGIS elements? Hope this helps, thanks
    – LiamHems
    Dec 17, 2020 at 12:21
  • 2
    Aha ... you need to set PATH correctly. Take a look at following link that I explained how we can use ArcGIS Python (ArcPy) oustside ArcGIS software. gis.stackexchange.com/questions/330390/…
    – ArashMad
    Dec 17, 2020 at 12:24
  • In a Windows .bat file, a back-slash (\) is probably safer than a normal slash (/) for path separator characters. Python handles either, and most operating systems use a normal slash, but Windows (inc. .bat files) generally use a back-slash as a file separator and a normal slash to signify a command operator. (Although Windows/DOS is not entirely consistent and can use a normal slash as a path separator in some situations.) Dec 21, 2020 at 0:25
  • @ArashMad I have created a .bat file like listed above but when I try to run it, it says that the directory file name is invalid, system cannot find the specified file. Have I not set the right PATH correctly?
    – LiamHems
    Jan 4, 2021 at 13:41
  • Which machine do you try on @LiamHems? Can you run commands directly inside command line window? I just edited the code. Try "\" instead of "/" as suggested by others. cd C:\users\user\desktop then C:\Python35\python.exe .\test.py
    – ArashMad
    Jan 4, 2021 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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