| 1 |
""" |
| 2 |
A quick hack to capture stdout/stderr. |
| 3 |
""" |
| 4 |
from __future__ import print_function |
| 5 |
|
| 6 |
import os, sys |
| 7 |
|
| 8 |
|
| 9 |
class Capture: |
| 10 |
|
| 11 |
def __init__(self, mixed_out_err = False): |
| 12 |
"Start capture of the Unix-level stdout and stderr." |
| 13 |
if (sys.platform == 'win32' or |
| 14 |
not hasattr(os, 'tmpfile') or |
| 15 |
not hasattr(os, 'dup') or |
| 16 |
not hasattr(os, 'dup2') or |
| 17 |
not hasattr(os, 'fdopen')): |
| 18 |
self.dummy = 1 |
| 19 |
else: |
| 20 |
self.dummy = 0 |
| 21 |
|
| 22 |
self.localoutfd = os.dup(1) |
| 23 |
self.localerrfd = os.dup(2) |
| 24 |
if hasattr(sys.stdout, 'fileno') and sys.stdout.fileno() == 1: |
| 25 |
self.saved_stdout = sys.stdout |
| 26 |
sys.stdout = os.fdopen(self.localoutfd, 'w', 1) |
| 27 |
else: |
| 28 |
self.saved_stdout = None |
| 29 |
if hasattr(sys.stderr, 'fileno') and sys.stderr.fileno() == 2: |
| 30 |
self.saved_stderr = sys.stderr |
| 31 |
sys.stderr = os.fdopen(self.localerrfd, 'w', 0) |
| 32 |
else: |
| 33 |
self.saved_stderr = None |
| 34 |
self.tmpout = os.tmpfile() |
| 35 |
if mixed_out_err: |
| 36 |
self.tmperr = self.tmpout |
| 37 |
else: |
| 38 |
self.tmperr = os.tmpfile() |
| 39 |
os.dup2(self.tmpout.fileno(), 1) |
| 40 |
os.dup2(self.tmperr.fileno(), 2) |
| 41 |
|
| 42 |
def done(self): |
| 43 |
"End capture and return the captured text (stdoutfile, stderrfile)." |
| 44 |
if self.dummy: |
| 45 |
import cStringIO |
| 46 |
return cStringIO.StringIO(), cStringIO.StringIO() |
| 47 |
else: |
| 48 |
os.dup2(self.localoutfd, 1) |
| 49 |
os.dup2(self.localerrfd, 2) |
| 50 |
if self.saved_stdout is not None: |
| 51 |
f = sys.stdout |
| 52 |
sys.stdout = self.saved_stdout |
| 53 |
f.close() |
| 54 |
else: |
| 55 |
os.close(self.localoutfd) |
| 56 |
if self.saved_stderr is not None: |
| 57 |
f = sys.stderr |
| 58 |
sys.stderr = self.saved_stderr |
| 59 |
f.close() |
| 60 |
else: |
| 61 |
os.close(self.localerrfd) |
| 62 |
self.tmpout.seek(0) |
| 63 |
self.tmperr.seek(0) |
| 64 |
return self.tmpout, self.tmperr |
| 65 |
|
| 66 |
|
| 67 |
if __name__ == '__main__': |
| 68 |
|
| 69 |
c = Capture() |
| 70 |
try: |
| 71 |
os.system('echo hello') |
| 72 |
finally: |
| 73 |
fout, ferr = c.done() |
| 74 |
print('Output:', `fout.read()`) |
| 75 |
print('Error:', `ferr.read()`) |