Skip to content

Instantly share code, notes, and snippets.

@basilevs
Last active October 13, 2015 21:07
Show Gist options
  • Select an option

  • Save basilevs/4255972 to your computer and use it in GitHub Desktop.

Select an option

Save basilevs/4255972 to your computer and use it in GitHub Desktop.
Redirect all current process output to a file
#!/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)
@basilevs
Copy link
Author

The main point is redirection of used C libraries output which is not processed by Python routines (raw system writes).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment