I'm writing a python program that will run in a container, I'm sharing a directory with this container to save all logs. But I can't redirect the output.
Are there a way inside the python code to redirect all output to file?
Python 2.7
I'm writing a python program that will run in a container, I'm sharing a directory with this container to save all logs. But I can't redirect the output.
Are there a way inside the python code to redirect all output to file?
Python 2.7
 
    
    If this is just for some development testing, this should work ok.
>>> import sys
>>> f = open("/tmp/stdout", "w")
>>> sys.stdout = f
>>> print "Hello"
>>> print "Whoa"
> cat /tmp/stdout
Hello
Whoa
You may want to periodically call sys.stdout.flush() to get more real-time output.
You could also use a wrapper like this (stolen from Disable output buffering):
class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)
Then you would do
sys.stdout = Unbuffered(open("/tmp/stdout", "w"))
print "foo"
print "bar"
if you need sys.stdout back, you should be able to do
sys.stdout = sys.__stdout__
You can give a file handle to sys.stdout and sys.stderr to redirect the output or errors to a file.
For example:
stdo=sys.stdout
# need a file handle with write mode
fhandle=open("out.txt",'w');
sys.stdout=fhandle
print "I'm the output~"
......
# reset the standard output
sys.stdout=stdo
 
    
    If you want both at the same time you can do this
class OutputLogger(object):
    def __init__(self, output_file='/tmp/output_file.txt'):
        self.std = sys.stdout
        self.outfile = open(output_file, 'w')
    def write(self, message):
        self.std.write(message)
        self.outfile.write(message)
    def flush(self):
        self.outfile.flush()
        self.std.flush()
And use it like
import sys
sys.stdout = OutputLogger(path_to_file)
print 'Hello Logger'
