Skip to content

Commit

Permalink
BUG: Avoid segfault if importing qt & ctk python package in standalon…
Browse files Browse the repository at this point in the history
…e python

Since importing a PythonQt-based module outside of a Qt application
leads to a segfault, skip the import if it happens in a standalone
python interpreter.

See commontk#520
  • Loading branch information
jcfr committed Mar 14, 2023
1 parent eaa9200 commit da08630
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
12 changes: 11 additions & 1 deletion Libs/Scripting/Python/Core/Python/ctk/__init__.py.in
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,22 @@ its namespace."""

__kits_to_load = [ @CTK_PYTHON_WRAPPED_LIBRARIES@ ]

import os
import sys
_standalone_python = "python" in str.lower(os.path.split(sys.executable)[-1])

# Set to True when debugging
_CTK_VERBOSE_IMPORT = False

kits = []
for kit in __kits_to_load:
try:
# Since importing a PythonQt-based module outside of a Qt application
# leads to a segfault, skip the import if it happens in a standalone
# python interpreter.
# See https://github.com/commontk/CTK/pull/520
if _standalone_python:
continue
exec("from CTK%sPythonQt import *" % kit)
kits.append(kit)
except ImportError as detail:
Expand Down Expand Up @@ -103,6 +113,6 @@ if _lib == 'Widgets':
decorates_ctkWorkflowWidgetStep_initialize_method()

# Removing things the user shouldn't have to see.
del __kits_to_load, _lib, _CTK_VERBOSE_IMPORT
del __kits_to_load, _lib, _standalone_python, _CTK_VERBOSE_IMPORT
del add_methodclass_to_ctkWorkflowStep_or_ctkWorkflowWidgetStep
del add_methodclass_to_ctkWorkflowWidgetStep, decorates_ctkWorkflowWidgetStep_initialize_method
14 changes: 12 additions & 2 deletions Libs/Scripting/Python/Core/Python/qt/__init__.py.in
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,28 @@ its namespace."""

__kits_to_load = [ @QT_PYTHON_WRAPPED_LIBRARIES@ ]

import os
import sys
_standalone_python = "python" in str.lower(os.path.split(sys.executable)[-1])

# Set to True when debugging
_CTK_VERBOSE_IMPORT = False

for kit in __kits_to_load:
# Since importing a PythonQt-based module outside of a Qt application
# leads to a segfault, skip the import if it happens in a standalone
# python interpreter.
# See https://github.com/commontk/CTK/pull/520
if _standalone_python:
continue
try:
exec("from PythonQt.Qt%s import *" % kit)
except ImportError as detail:
if _CTK_VERBOSE_IMPORT:
print(detail)

if "QObject" not in locals():
if "QObject" not in locals() and not _standalone_python:
from PythonQt.private import QObject

# Removing things the user shouldn't have to see.
del __kits_to_load, _CTK_VERBOSE_IMPORT
del __kits_to_load, _standalone_python, _CTK_VERBOSE_IMPORT

0 comments on commit da08630

Please sign in to comment.