I have a Python script which processes data with geographic information. At some stage of my script I need to use an instance of QGiS to make some shapefiles and do some intersects and so on. For now, I have created an instance of QGiS at the beginning, as it is written to do in documentation, however like this I free the memory and remove data providers and memory layer at the end of my script.
qgs = QgsApplication(sys.argv, True)
qgs.initQgis()
startScripting()
qgs.exec_()
qgs.exitQgis()
It is working, but unfortunately from time to time data from previous processing are also used in next processing.
In startScripting()
I have a for loop:
for pro in users[idUser].keys():
[result] = rep.report(users[idUser][pro],idUser,pro)
And all geographic data are process there (in report()). So to be honest I need to create instance of QGiS in for loop to have a clear instance to proceed. I have tried something like this:
for pro in users[idUser].keys():
qgs = QgsApplication(sys.argv, True)
qgs.initQgis()
[result] = rep.report(users[idUser][pro],idUser,pro)
qgs.exec_()
qgs.exitQgis()
Of course I have deleted creating instance of QGiS at the beginning in this solution.
However if I try creating QGiS instance in for loop, then everything is fine but only for first loop, the second one doesn't start. I think that qgs.exitQgis() stop my whole script.
Maybe I do something the wrong way? Or maybe there is another way to clear data providers, memory layers, without closing instance of QGiS?
1 Answer 1
I had the same problem, and the only solution I found is to create a second script which calls the first one with the subprocess module.
So in script1.py
import sys
qgs = QgsApplication(sys.argv, True)
qgs.initQgis()
pro = sysargv[1]
[result] = rep.report(users[idUser][pro],idUser, pro)
qgs.exec_()
qgs.exitQgis()
and script2.py
import subprocess as sp
for pro in users[idUser].keys():
sp.run(['python','script1.py', pro])