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:
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).
I ran qgis --code myscript.py at the bash console, inside the folder of the script, and immediately I got this error message:
and indicating that from qgis.utils import iface line is necessary.
When the first line is not commented the script execution had not errors:
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:
and use the Control Panel of Windows to change it.