Skip to content

Commit

Permalink
[python] Don't install error hook by default
Browse files Browse the repository at this point in the history
This error hook should only ever be used from QGIS app, never
from standalone scripts and applications, so we should default
to not using it and only install it when initializing python
from app.

Otherwise default behavior for standalone scripts based on
PyQGIS is to silently swallow exceptions - this leaves script
developers *no clues* to go off to debug their applications,
meaning that errors which would usually take a couple of seconds
to fix become horrible exercises in frustration for those
unaware of QGIS' exception handling and the
QGIS_DISABLE_MESSAGE_HOOKS environment variable.

Refs #19111
  • Loading branch information
nyalldawson committed Jun 5, 2018
1 parent cbbe905 commit 40a2062
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 10 deletions.
13 changes: 5 additions & 8 deletions python/utils.py
Expand Up @@ -77,10 +77,6 @@ def showWarning(message, category, filename, lineno, file=None, line=None):
)


if not os.environ.get('QGIS_DISABLE_MESSAGE_HOOKS'):
warnings.showwarning = showWarning


def showException(type, value, tb, msg, messagebar=False):
if msg is None:
msg = QCoreApplication.translate('Python', 'An error has occurred while executing Python code:')
Expand Down Expand Up @@ -198,17 +194,18 @@ def qgis_excepthook(type, value, tb):


def installErrorHook():
"""
Installs the QGIS application error/warning hook
:return:
"""
sys.excepthook = qgis_excepthook
warnings.showwarning = showWarning


def uninstallErrorHook():
sys.excepthook = sys.__excepthook__


# install error hook() on module load
if not os.environ.get('QGIS_DISABLE_MESSAGE_HOOKS'):
installErrorHook()

# initialize 'iface' object
iface = None

Expand Down
4 changes: 2 additions & 2 deletions src/python/qgspythonutilsimpl.cpp
Expand Up @@ -224,6 +224,7 @@ void QgsPythonUtilsImpl::initPython( QgisInterface *interface )
return;
}
doCustomImports();
installErrorHook();
finish();
}

Expand Down Expand Up @@ -264,6 +265,7 @@ bool QgsPythonUtilsImpl::startServerPlugin( QString packageName )

void QgsPythonUtilsImpl::exitPython()
{
uninstallErrorHook();
Py_Finalize();
mMainModule = nullptr;
mMainDict = nullptr;
Expand All @@ -286,8 +288,6 @@ void QgsPythonUtilsImpl::uninstallErrorHook()
runString( QStringLiteral( "qgis.utils.uninstallErrorHook()" ) );
}



bool QgsPythonUtilsImpl::runStringUnsafe( const QString &command, bool single )
{
// acquire global interpreter lock to ensure we are in a consistent state
Expand Down

0 comments on commit 40a2062

Please sign in to comment.