2

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.

10
  • How about using redirection? python script_name.py > output.txt Commented Jan 3, 2014 at 6:52
  • Redirection works on windows 7 Commented Jan 3, 2014 at 6:53
  • 1
    You might want to use the logging module. Commented Jan 3, 2014 at 6:54
  • But I want to run the script inside the script, not from command line. Commented Jan 3, 2014 at 6:54
  • 1
    @alwbtc Make logging.log calls instead of prints, this wasn't meant solve your exact problem, but it seems appropriate for debugging Commented Jan 3, 2014 at 6:56

1 Answer 1

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" 
Sign up to request clarification or add additional context in comments.

4 Comments

Great. Could you please show how to write both to console and file? Because your answer just writes to file.
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?
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.
Sir, thank you. Do big python software projects handle loggings this way?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.