Saturday 21 January 2017

python - How to set conditional imports for a PyQGis script running inner or outer of QGIS?


Related to Import error for qgis.core when running OSGeo4w shell script


I try to detect if my script is run from a QGIS instance (through the plugin) or from a standard python console. This detection will enable conditional imports of the required librairies which are different from a case to the other.



For conditional imports, I found here


try:
import module
except ImportError:
import otherModule as module

and tried to adapt it for my use case but I can't raise a convenient error:


E.G.


try:
import processing


except:
# Load required libraries to run from python (!Unstable!)
# See https://gis.stackexchange.com/questions/129915/cannot-run-standalone-qgis-script
# for any improvements
import os, sys, glob

# Prepare the environment
...
# See https://gis.stackexchange.com/questions/129915/cannot-run-standalone-qgis-script


Returns me following error : QPixmap: Must construct a QApplication before a QPaintDevice


and does not instead enters the except clause what is sad.



Answer



The error QPixmap: Must construct a QApplication before a QPaintDevice seems to be related to the fact you don't declare a QApplication before your try/except statement.


The other issue about try except is only about Python.


You can manage error correctly with:


try:
# To be sure it fails
import processing1

except Exception, e:
print type(e), e

You will see that you can catch various exceptions types. There is one specific import error. Hence, above try/except could be improve with:


try:
# To be sure it fails
import processing1
except ImportError, e:
print type(e), e
else:

print "Other error"

Edit: Although my answer was correct, it wasn't enough to help.


You can do the following to differentiate context:


try:
canvas = iface.mapCanvas()
print 'You are in a QGIS console'
except Exception, e:
print 'You are in an external script', e


iface is imported only in a QGIS console context e.g the official docs http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html#python-console


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...