Created
September 26, 2013 10:33
-
-
Save chengui/6712444 to your computer and use it in GitHub Desktop.
capture stdout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import tempfile | |
import os | |
class captured_stdout: | |
def __init__(self): | |
self.prevfd = None | |
self.prev = None | |
def __enter__(self): | |
F = tempfile.NamedTemporaryFile() | |
self.prevfd = os.dup(sys.stdout.fileno()) | |
os.dup2(F.fileno(), sys.stdout.fileno()) | |
self.prev = sys.stdout | |
sys.stdout = os.fdopen(self.prevfd, "w") | |
return F | |
def __exit__(self, exc_type, exc_value, traceback): | |
os.dup2(self.prevfd, self.prev.fileno()) | |
sys.stdout = self.prev | |
## | |
## Example usage | |
## | |
## here is a hack to print directly to stdout | |
import ctypes | |
libc=ctypes.LibraryLoader(ctypes.CDLL).LoadLibrary("libc.so.6") | |
def directfdprint(s): | |
libc.write(1, s, len(s)) | |
print("I'm printing from python before capture") | |
directfdprint("I'm printing from libc before captrue\n") | |
with captured_stdout() as E: | |
print("I'm printing from python in capture") | |
directfdprint("I'm printing from libc in capture\n") | |
print("I'm printing from python after capture") | |
directfdprint("I'm printing from libc after captrue\n") | |
print("Capture contains: " + repr(file(E.name).read())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment