55import inspect
66import sys
77import warnings
8+ from contextlib import redirect_stderr
9+ from contextlib import redirect_stdout
810from functools import partial
11+ from io import StringIO
912from typing import TYPE_CHECKING
1013from typing import Any
1114from typing import Callable
@@ -98,6 +101,8 @@ def _execute_task( # noqa: PLR0913
98101 PyTree [PythonNode | None ],
99102 list [WarningReport ],
100103 tuple [type [BaseException ], BaseException , str ] | None ,
104+ str ,
105+ str ,
101106]:
102107 """Unserialize and execute task.
103108
@@ -111,8 +116,13 @@ def _execute_task( # noqa: PLR0913
111116 # Patch set_trace and breakpoint to show a better error message.
112117 _patch_set_trace_and_breakpoint ()
113118
119+ captured_stdout_buffer = StringIO ()
120+ captured_stderr_buffer = StringIO ()
121+
114122 # Catch warnings and store them in a list.
115- with warnings .catch_warnings (record = True ) as log :
123+ with warnings .catch_warnings (record = True ) as log , redirect_stdout (
124+ captured_stdout_buffer
125+ ), redirect_stderr (captured_stderr_buffer ):
116126 # Apply global filterwarnings.
117127 for arg in session_filterwarnings :
118128 warnings .filterwarnings (* parse_warning_filter (arg , escape = False ))
@@ -146,12 +156,25 @@ def _execute_task( # noqa: PLR0913
146156 )
147157 )
148158
159+ captured_stdout_buffer .seek (0 )
160+ captured_stderr_buffer .seek (0 )
161+ captured_stdout = captured_stdout_buffer .read ()
162+ captured_stderr = captured_stderr_buffer .read ()
163+ captured_stdout_buffer .close ()
164+ captured_stderr_buffer .close ()
165+
149166 # Collect all PythonNodes that are products to pass values back to the main process.
150167 python_nodes = tree_map (
151168 lambda x : x if isinstance (x , PythonNode ) else None , task .produces
152169 )
153170
154- return python_nodes , warning_reports , processed_exc_info
171+ return (
172+ python_nodes ,
173+ warning_reports ,
174+ processed_exc_info ,
175+ captured_stdout ,
176+ captured_stderr ,
177+ )
155178
156179
157180def _process_exception (
0 commit comments