Last active
October 13, 2015 21:07
-
-
Save basilevs/4255972 to your computer and use it in GitHub Desktop.
Redirect all current process output to a file
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
| #!/usr/bin/python | |
| # coding: utf-8 | |
| from sys import stderr, stdout | |
| from os import dup, dup2, close | |
| from subprocess import Popen, PIPE | |
| from contextlib import contextmanager | |
| from time import sleep | |
| from traceback import print_exc | |
| @contextmanager | |
| def copyOutput(file): | |
| print "Output is logged to", file | |
| stdout.flush() | |
| stderr.flush() | |
| tee=Popen(['tee', file], stdin=PIPE, preexec_fn=setpgrp) | |
| out = dup(stdout.fileno()) | |
| err = dup(stderr.fileno()) | |
| dup2(tee.stdin.fileno(), stdout.fileno()) | |
| dup2(tee.stdin.fileno(), stderr.fileno()) | |
| try: | |
| yield | |
| except: | |
| stdout.flush() | |
| stderr.flush() | |
| print_exc() | |
| finally: | |
| stdout.flush() | |
| stderr.flush() | |
| dup2(out, stdout.fileno()) | |
| dup2(err, stderr.fileno()) | |
| close(out) | |
| close(err) | |
| tee.stdin.close() | |
| tee.wait() | |
| print file, "closed" | |
| print "Writing to standard output" | |
| with redirectOutput('/tmp/out.log'): | |
| print "Writing to both standard output and file" | |
| print "Writing to standard output" | |
| sleep(10) | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The main point is redirection of used C libraries output which is not processed by Python routines (raw system writes).