[GIS] How to exit QGIS after running a python script

pyqgispythonqgis

I would like to run a python script via qgis --code myscript.py and then immediately exit. I'm using iface.actionExit().trigger(), which kills QGIS when I run it from the python console, but not when put in the script that I pass to --code.

What's the right way to immediately exit? I'm running QGIS 2.0.1

Update: I've also tried sys.exit(). QGIS catches it and pops up a window with the following:

An error occured during execution of following code:
  execfile('myscript.py')

  Traceback (most recent call last):
    File "", line 1, in 
    File "myscript.py", line 14, in 
      sys.exit()
  SystemExit

Update: os.kill(os.getpid(), 9) works but it's a dirty hack and I'm looking for something better.

Best Answer

Try in your script:

from qgis.utils import iface

#your code here

iface.actionExit().trigger()

It works for me.

Editing Note:

Based in Conley Owens'comment, I changed slightly my script to do "something useful" (where the line that import iface was commented).

#from qgis.utils import iface
import os

os.system('clear')
print "Hello"

iface.actionExit().trigger()

I ran qgis --code myscript.py at the bash console, inside the folder of the script, and immediately I got this error message:

enter image description here

and indicating that from qgis.utils import iface line is necessary.

When the first line is not commented the script execution had not errors:

enter image description here

but the control was not in the Python console; it is in the bash console (observe the "Hello" print there). For this reason your os.kill(os.getpid(), 9) command works because close the console and automatically close QGIS.

The solution to this issue, if I need the PyQGIS API outside QGIS, it was to include the PYTHONPATH to QGIS (/usr/share/qgis/python) in my .bashrc and to run the script in the bash console as python myscript.py. It works.

In Windows, you can get the PYTHONPATH in the Python Console of QGIS with:

import os
os.getcwd()

and use the Control Panel of Windows to change it.

Related Question