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")

LiamHems
  • 193
  • 13
  • 5
    https://docs.qgis.org/3.16/en/docs/pyqgis_developer_cookbook/intro.html#using-pyqgis-in-standalone-scripts – BERA Dec 15 '20 at 11:43
  • 1
    Please provide just a code snippet that illustrates what you want to do rather than your whole script. – PolyGeo Dec 15 '20 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 '20 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 '20 at 12:03
  • so. Does it work yes/no and what error messages do you get if any? – Fee Dec 15 '20 at 16:34
  • I have tried it but when I double click the script to run it, the console goes off straight away and does nothing. Using pycharm, it states that there is no module called qgis, so not too sure what the next step is – LiamHems Dec 15 '20 at 20:31
  • Do you mean running .py script using a third-party IDE like Pycharm or VS Code? – ArashMad Dec 17 '20 at 12:01
  • @ArashMadadi Hi Arash, my final goal is to create a .bat file that runs in task scheduler every minute, so I would preferably want to run the script using a .bat file but just double clicking the .py script in my files and running the script that way would also work for me. I do have PyCharm so if the code works on there, then I should be able to just double click the file and run the script that way, right? Hope this makes sense? Thanks – LiamHems Dec 17 '20 at 12:07
  • 2
    check this https://gis.stackexchange.com/a/289964/49538 – Fran Raga Dec 17 '20 at 12:49

1 Answers1

3

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
ArashMad
  • 655
  • 5
  • 10
  • 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 '20 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. https://gis.stackexchange.com/questions/330390/arcpy-script-causes-python-crash-when-run-outside-of-arcgis-python-window/372778#372778 – ArashMad Dec 17 '20 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.) – Son of a Beach Dec 21 '20 at 00: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 04 '21 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 04 '21 at 14:14
  • I am on a Windows computer. Normally I can run commands within the command prompt but unfortunately this time, it says the directory is invalid and the file cannot be specified, hmm... Do you know another way that I can import Qgs modules into PyCharm, as currently it just states that there is no module called qgis and errors followed after are just because they are included within QGIS, such as QgsVectorLayer or QgsRasterLayer etc? Thanks – LiamHems Jan 04 '21 at 14:20
  • @LiamHems To avoid a long list of comments, join this: https://chat.stackexchange.com/rooms/939/gis and express the problem there. – ArashMad Jan 04 '21 at 14:28