context manager for capturing stdout/err
| 129 | |
| 130 | |
| 131 | class capture_output: |
| 132 | """context manager for capturing stdout/err""" |
| 133 | stdout = True |
| 134 | stderr = True |
| 135 | display = True |
| 136 | |
| 137 | def __init__(self, stdout: bool=True, stderr: bool=True, display: bool=True): |
| 138 | self.stdout = stdout |
| 139 | self.stderr = stderr |
| 140 | self.display = display |
| 141 | self.shell = None |
| 142 | |
| 143 | def __enter__(self) -> CapturedIO: |
| 144 | from IPython.core.getipython import get_ipython |
| 145 | from IPython.core.displaypub import CapturingDisplayPublisher |
| 146 | from IPython.core.displayhook import CapturingDisplayHook |
| 147 | |
| 148 | self.sys_stdout = sys.stdout |
| 149 | self.sys_stderr = sys.stderr |
| 150 | |
| 151 | if self.display: |
| 152 | self.shell = get_ipython() |
| 153 | if self.shell is None: |
| 154 | self.save_display_pub = None |
| 155 | self.display = False |
| 156 | |
| 157 | stdout = stderr = outputs = None |
| 158 | if self.stdout: |
| 159 | stdout = sys.stdout = StringIO() |
| 160 | if self.stderr: |
| 161 | stderr = sys.stderr = StringIO() |
| 162 | if self.display: |
| 163 | self.save_display_pub = self.shell.display_pub |
| 164 | self.shell.display_pub = CapturingDisplayPublisher() |
| 165 | outputs = self.shell.display_pub.outputs |
| 166 | self.save_display_hook = sys.displayhook |
| 167 | sys.displayhook = CapturingDisplayHook(shell=self.shell, |
| 168 | outputs=outputs) |
| 169 | |
| 170 | return CapturedIO(stdout, stderr, outputs) |
| 171 | |
| 172 | def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]): |
| 173 | sys.stdout = self.sys_stdout |
| 174 | sys.stderr = self.sys_stderr |
| 175 | if self.display and self.shell: |
| 176 | self.shell.display_pub = self.save_display_pub |
| 177 | sys.displayhook = self.save_display_hook |
no outgoing calls
searching dependent graphs…