Skip to content

Commit 40a2062

Browse files
committed
[python] Don't install error hook by default
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
1 parent cbbe905 commit 40a2062

File tree

2 files changed

+7
-10
lines changed

2 files changed

+7
-10
lines changed

python/utils.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,6 @@ def showWarning(message, category, filename, lineno, file=None, line=None):
7777
)
7878

7979

80-
if not os.environ.get('QGIS_DISABLE_MESSAGE_HOOKS'):
81-
warnings.showwarning = showWarning
82-
83-
8480
def showException(type, value, tb, msg, messagebar=False):
8581
if msg is None:
8682
msg = QCoreApplication.translate('Python', 'An error has occurred while executing Python code:')
@@ -198,17 +194,18 @@ def qgis_excepthook(type, value, tb):
198194

199195

200196
def installErrorHook():
197+
"""
198+
Installs the QGIS application error/warning hook
199+
:return:
200+
"""
201201
sys.excepthook = qgis_excepthook
202+
warnings.showwarning = showWarning
202203

203204

204205
def uninstallErrorHook():
205206
sys.excepthook = sys.__excepthook__
206207

207208

208-
# install error hook() on module load
209-
if not os.environ.get('QGIS_DISABLE_MESSAGE_HOOKS'):
210-
installErrorHook()
211-
212209
# initialize 'iface' object
213210
iface = None
214211

src/python/qgspythonutilsimpl.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ void QgsPythonUtilsImpl::initPython( QgisInterface *interface )
224224
return;
225225
}
226226
doCustomImports();
227+
installErrorHook();
227228
finish();
228229
}
229230

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

265266
void QgsPythonUtilsImpl::exitPython()
266267
{
268+
uninstallErrorHook();
267269
Py_Finalize();
268270
mMainModule = nullptr;
269271
mMainDict = nullptr;
@@ -286,8 +288,6 @@ void QgsPythonUtilsImpl::uninstallErrorHook()
286288
runString( QStringLiteral( "qgis.utils.uninstallErrorHook()" ) );
287289
}
288290

289-
290-
291291
bool QgsPythonUtilsImpl::runStringUnsafe( const QString &command, bool single )
292292
{
293293
// acquire global interpreter lock to ensure we are in a consistent state

0 commit comments

Comments
 (0)