3

I have a python script, it contains print statements here and there for debugging purposes. Now I find it hard to read them in console. Does python have any libraries which will automatically direct all print statements' outputs to a specified text file? I use Windows 7 by the way, not Linux. I also don't run my scripts from command line.

So what I want is something like below:

import logger_module

log_file = "log.txt"
logger_module.activate_logging(log_file)

print "blablabla"

When I run the script above, I should see "blablabla" in log.txt file.

alwbtc
  • 28,057
  • 62
  • 134
  • 188

1 Answers1

2

I believe this is the closest you'll get:

import sys
sys.stdout = open('file', 'w')
print 'test' # prints test to file

If you'd like to write to multiple locations, you can use the following. Any object with a write method can be assigned to sys.stdout in python.

import sys

class Logger(object):
    def __init__(self, *files):
        self.files = files

    def write(self, obj):
        for f in self.files:
            f.write(obj)

f = open('file', 'w')
sys.stdout = Logger(f, sys.stdout)

print "Python Magic"
Madison May
  • 2,723
  • 3
  • 22
  • 32
  • Great. Could you please show how to write both to console and file? Because your answer just writes to file. – alwbtc Jan 03 '14 at 07:18
  • Thanks for the edit, but I didn't mean multiple files, I wanted to to say, how to write both to a file and to the shell window? – alwbtc Jan 03 '14 at 07:39
  • That code should work for that purpose. The shell window is more or less a "file" in the sense that you can write to it. Give it a go and let me know if it works for you. – Madison May Jan 03 '14 at 07:40
  • Sir, thank you. Do big python software projects handle loggings this way? – alwbtc Jan 03 '14 at 09:09