no the print in the experiment and result script are also printed

This commit is contained in:
2026-07-13 23:19:10 +02:00
parent 1bb92a9157
commit 9b9a0ec1df
4 changed files with 59 additions and 9 deletions
+36 -1
View File
@@ -13,17 +13,41 @@ logger = logging.getLogger("damaris.experiment_handling")
class StopExperiment(Exception):
pass
class _SandboxStdout:
"""Redirects print() from sandboxed scripts to the GUI textview."""
def __init__(self, callback):
self._callback = callback
self._buffer = ""
def write(self, message):
self._buffer += message
if "\n" in self._buffer:
lines = self._buffer.split("\n")
self._buffer = lines[-1]
for line in lines[:-1]:
self._callback(line + "\n")
def flush(self):
if self._buffer:
self._callback(self._buffer)
self._buffer = ""
def isatty(self):
return False
class ExperimentHandling(threading.Thread):
"""
runs the experiment script in sandbox
"""
def __init__(self, script, exp_writer, data):
def __init__(self, script, exp_writer, data, log_callback=None):
threading.Thread.__init__(self, name="experiment handler")
self.script=script
self.writer=exp_writer
self.data=data
self.quit_flag = threading.Event()
self._log_callback = log_callback
if self.data is not None:
self.data["__recentexperiment"]=-1
@@ -53,6 +77,13 @@ class ExperimentHandling(threading.Thread):
self.location = None
exp_iterator=None
# Redirect stdout/stderr so print() in sandboxed scripts goes to the GUI
_orig_stdout = sys.stdout
_orig_stderr = sys.stderr
if self._log_callback is not None:
sys.stdout = _SandboxStdout(self._log_callback)
sys.stderr = _SandboxStdout(self._log_callback)
# check for time.sleep()
try:
tree = ast.parse(self.script)
@@ -150,3 +181,7 @@ class ExperimentHandling(threading.Thread):
dataspace=None
self.exp_iterator=None
self.writer=None
# Restore stdout/stderr
sys.stdout = _orig_stdout
sys.stderr = _orig_stderr