From f873b38e8f194e8fbd57e803954f7996343b52c7 Mon Sep 17 00:00:00 2001 From: George Gevoian Date: Tue, 13 Jun 2023 09:40:55 -0400 Subject: [PATCH] (core) Use fake stdout/stderr when evaluating formulas Summary: In the future, it may be helpful to capture some output to display in the formula editor (e.g. the result of calling print()), but for now it's best to redirect stdout/stderr to avoid excessive logging. Test Plan: Tested manually. Reviewers: alexmojaki Reviewed By: alexmojaki Subscribers: alexmojaki Differential Revision: https://phab.getgrist.com/D3919 --- sandbox/grist/engine.py | 7 +++++-- sandbox/grist/fake_std_streams.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 sandbox/grist/fake_std_streams.py diff --git a/sandbox/grist/engine.py b/sandbox/grist/engine.py index 7f4926bc..c5ddf87d 100644 --- a/sandbox/grist/engine.py +++ b/sandbox/grist/engine.py @@ -24,6 +24,7 @@ from codebuilder import DOLLAR_REGEX import depend import docactions import docmodel +from fake_std_streams import FakeStdStreams import gencode import logger import match_counter @@ -944,9 +945,11 @@ class Engine(object): raise depend.CircularRefError("Circular Reference") if not col.is_formula(): value = col.get_cell_value(int(record), restore=True) - result = col.method(record, table.user_table, value, self._user) + with FakeStdStreams(): + result = col.method(record, table.user_table, value, self._user) else: - result = col.method(record, table.user_table) + with FakeStdStreams(): + result = col.method(record, table.user_table) if self._cell_required_error: raise self._cell_required_error # pylint: disable=raising-bad-type self.formula_tracer(col, record) diff --git a/sandbox/grist/fake_std_streams.py b/sandbox/grist/fake_std_streams.py new file mode 100644 index 00000000..e15a0a99 --- /dev/null +++ b/sandbox/grist/fake_std_streams.py @@ -0,0 +1,18 @@ +import sys + +import six + + +class FakeStdStreams(object): + """ + Redirects stdout and stderr to StringIO. + """ + def __enter__(self): + self._orig_stdout = sys.stdout + self._orig_stderr = sys.stderr + sys.stdout = six.StringIO() + sys.stderr = six.StringIO() + + def __exit__(self, exc_type, exc_val, exc_tb): + sys.stdout = self._orig_stdout + sys.stderr = self._orig_stderr