1

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.

Nono
  • 473
  • 4
  • 12

1 Answers1

2

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

ThomasG77
  • 30,725
  • 1
  • 53
  • 93
  • The goal is to detect if we are on Qgis console or on an extern python console (because imports are different). That's why I tried to generate an error. But the "QPixmap: Must construct a QApplication before a QPaintDevice" makes the console crash and the error handling does not goes through the except clause as it should in a good error management system. – Nono Jan 21 '16 at 22:55
  • Great, ty for the edit! I went other the docs, but not carefully enough! – Nono Jan 22 '16 at 12:23