blob: 0003a8a69564e7d74ecac2d652ab683315009494 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# vim: set fileencoding=utf-8 :
import sys
from contextlib import contextmanager
from io import StringIO
class _StderrCapture(StringIO):
def save(self):
self.safed = sys.stdout
sys.stderr = self
def restore(self):
if self.safed is not None:
sys.stderr = self.safed
self.safed = None
def output(self):
self.seek(0)
return self.read()
class _StdoutCapture(StringIO):
def save(self):
self.safed = sys.stdout
sys.stdout = self
def restore(self):
if self.safed is not None:
sys.stdout = self.safed
self.safed = None
def output(self):
self.seek(0)
return self.read()
@contextmanager
def capture_stderr():
"""Capture an output and return its content"""
c = _StderrCapture()
c.save()
yield c
c.restore()
@contextmanager
def capture_stdout():
"""Capture an output and return its content"""
c = _StdoutCapture()
c.save()
yield c
c.restore()
|