I'm trying to find out a way in python to redirect the script execution log to a file as well as stdout
in a pythonic way. Is there any easy way of achieving this?
To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.
“tee” command is one of the most valuable tools that helps a Linux user redirect the output of a command to a file and screen. This article discussed the primary usage of “tee” for redirecting output to screen, single, or multiple files.
$ echo “Hello” > hello. txt The > command redirects the standard output to a file. Here, “Hello” is entered as the standard input, and is then redirected to the file **… $ cat deserts.
Append Text Using >> Operator The >> operator redirects output to a file, if the file doesn't exist, it is created but if it exists, the output will be appended at the end of the file. For example, you can use the echo command to append the text to the end of the file as shown.
Use logging module (http://docs.python.org/library/logging.html):
import logging logger = logging.getLogger('scope.name') file_log_handler = logging.FileHandler('logfile.log') logger.addHandler(file_log_handler) stderr_log_handler = logging.StreamHandler() logger.addHandler(stderr_log_handler) # nice output format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_log_handler.setFormatter(formatter) stderr_log_handler.setFormatter(formatter) logger.info('Info message') logger.error('Error message')
I came up with this [untested]
import sys class Tee(object): def __init__(self, *files): self.files = files def write(self, obj): for f in self.files: f.write(obj) f.flush() # If you want the output to be visible immediately def flush(self) : for f in self.files: f.flush() f = open('out.txt', 'w') original = sys.stdout sys.stdout = Tee(sys.stdout, f) print "test" # This will go to stdout and the file out.txt #use the original sys.stdout = original print "This won't appear on file" # Only on stdout f.close()
print>>xyz
in python will expect a write()
function in xyz
. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With