question 324 Decorators & Context Managers · easy
Capture what a function prints
An old report function prints its progress instead of logging it, and a scheduler wants to keep that text. Write run_captured(func, *args, **kwargs): call func with the arguments while capturing everything it prints, and return (result, lines), the function's return value and the printed text as a list of lines. If func raises, the exception propagates, and printing goes back to normal either way.
Function
run_captured(func, *args, **kwargs)Returns
(result, lines); lines from text.splitlines()Tools
io.StringIO and contextlib.redirect_stdout