redirect prints to log file
Solution 1
Python lets you capture and assign sys.stdout - as mentioned - to do this:
import sys
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print "this will be written to message.log"
sys.stdout = old_stdout
log_file.close()
Solution 2
You should take a look at python logging module
EDIT: Sample code:
import logging
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+",
format="%(asctime)-15s %(levelname)-8s %(message)s")
logging.info("hello")
Produce a file named "logfile" with content:
2012-10-18 06:40:03,582 INFO hello
Solution 3
Next time, you'll be happier if instead of using
print
statements at all you use thelogging
module from the start. It provides the control you want and you can have it write to stdout while that's still where you want it.-
Many people here have suggested redirecting stdout. This is an ugly solution. It mutates a global and—what's worse—it mutates it for this one module's use. I would sooner make a regex that changes all
print foo
toprint >>my_file, foo
and setmy_file
to either stdout or an actual file of my choosing.- If you have any other parts of the application that actually depend on writing to stdout (or ever will in the future but you don't know it yet), this breaks them. Even if you don't, it makes reading your module look like it does one thing when it actually does another if you missed one little line up top.
- Chevron print is pretty ugly, but not nearly as ugly as temporarily changing
sys.stdout
for the process. - Very technically speaking, a regex replacement isn't capable of doing this right (for example, it could make false positives if you are inside of a multiline string literal). However, it's apt to work, just keep an eye on it.
os.system
is virtually always inferior to using thesubprocess
module. The latter needn't invoke the shell, doesn't pass signals in a way that usually is unwanted, and can be used in a non-blocking manner.
Solution 4
You can create a log file and prepare it for writing. Then create a function:
def write_log(*args):
line = ' '.join([str(a) for a in args])
log_file.write(line+'\n')
print(line)
and then replace your print() function name with write_log()
Solution 5
A simple way to redirect stdout and stderr using the logging module is here: How do I duplicate sys.stdout to a log file in python?
![webminal.org](https://i.stack.imgur.com/Mx7jx.jpg?s=256&g=1)
webminal.org
Free and Open Source programmer. Projects include: FileSystem Projects and Free Online Linux Terminal
Updated on July 09, 2022Comments
-
webminal.org almost 2 years
Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of
print
statements before running a command usingos.system()
say something like,print "running command",cmd os.system(cmd)
Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remove all
print
statements - since some provide useful info for user) into a log file will be more useful? Any tricks or tips.-
webminal.org over 14 yearsi think simple code snippet provided by Michel will fulfill my requirements ...thank you all
-
Admin over 5 yearsI tried the accepted answer's code but didn't really work. stackoverflow.com/questions/54049235/…
-
-
Admin over 14 yearsYou can also do -- sys.stdout = sys.__stdout__ -- instead of using old_stdout.
-
Admin over 14 years+1 for the logging module. Gives you wayyyy more control than print statements.
-
Mike Graham over 14 yearsThis is a messy hack, but certainly possible. If you do use it, reset
sys.stdout
to its original value in thefinally
block of atry/finally
. -
Mike Graham over 14 yearsThis is true but awful and shouldn't be used.
-
Mike Graham over 14 yearsThough applicable, that recipe is stylistically, semantically, and conceptually awful.
-
Mike Graham over 14 years@007brendan, that assumes that
sys.stdout
starts assys.__stdout__
. That isn't a great assumption, someone else could be redirectingsys.stdout
for a purpose like this or for a more sane use, like a system where a whole app's stdout really shouldn't besys.__stdout__
. -
Mike Graham over 14 yearsThat solution is disgusting and not even entirely applicable (in that it writes to stdout and a file; OP only wants to write to a file.)
-
blokeley over 14 yearsPlease could you explain why this is "disgusting"? I know redirecting stdout is a bad idea but sometimes it's worth doing: this week I did it to run django on a server overnight for testing, and django's runserver command prints to stdout. Also, please test your opinion before posting because the solution in question does not write to stdout. I have just tested it again.
-
Mike Graham over 14 yearsThis is disgusting because it uses globals. This means that when you read
print foo
it doesn't do what you expect it to without reading where the global was changed, which might not even be in the same file as the print statement. It's unmodular because multiple things can't all do this sanely. You even acknowledge that it's a bad idea. When something should be printed to stdout but you want to redirect it, there are tools for this (like>
on the shell); when something should be written somewhere other than stdout, you should make your code write there instead. -
Mike Graham over 14 yearsI apologize about my statement about the code writing to a file and stdout. I was looking at a different solution in the same thread as you linked. My mistake.
-
Nandhini over 14 years@Mike Graham, hey i wrote that 8 years ago :), anyway why is that so awful ?
-
Mike Graham over 14 yearsI would avoid using something like that if I could possibly do so for a couple reasons. It changes a global value (
sys.stdout
) for local use and may have accidental, far-off, unexpected effects (this is the reason people avoid using global state). When it's done, it restores the value tosys.__stdout__
, which may and may not be whatsys.stdout
started as depending on if someone else was doing this sort of trick. It does not have a usage such that an unexpected exception won't leavesys.stdout
stuck at an unwanted value later. -
Mike Graham over 14 yearsThat being said, I'm sorry to have been uncivil. Though I honestly believe the best solution will not use this kind of technique, I was unduly harsh in my criticism.
-
Nandhini over 14 years@Mike Graham that is fine, criticism is good, and that hook is hack to divert all the prints of app if need be, in practical situation I have used it on some old apps which have print littered all around
-
blokeley over 14 yearsApology accepted. Thanks for the clarification. I agree one should avoid messing with globals. I have updated my original post to point out that the logging module should be used directly wherever possible. This is what I always intended but didn't say it explicitly until now.
-
Tom Swirly over 11 yearsYour solution doesn't in fact answer the question of "how to redirect output" at all! Go to that page - search (in vain) for any hint of how to redirect logging to a file. The actual solution is on the page for logging.config - but I defy you to locate it there. onlamp.com/pub/a/python/2005/06/02/logging.html might be a better example.
-
Admin over 11 years@TomSwirly at the bottom of the page: a link to docs.python.org/library/… gives you a page where
FileHandler
is explained -
Admin over 11 years@TomSwirly and the page also explain
basicConfig
-
Tom Swirly over 11 yearsYou're right, it is at the bottom of that page, but by being wrong I improved your answer, so it worked out!
-
Admin over 5 yearsI tried the code but didn't really work. What's wrong with this? stackoverflow.com/questions/54049235/…
-
user5824405 over 4 yearsworks! python3.6 also works, need to be careful to close the opened file at the end
-
RAVI D PARIKH over 3 yearsMichael's answer works on python3.8. Can define a custom print function using this.