Refactor capturing stderr into a context manager