I would like to do the opposite of what often people are stuck with (they cannot get the logging to the console). I would like to log to file or GUI (that's not a problem) but I want to suppress the log to the console. So, question, how do I log ONLY to file and NOT to Console?
Asked
Active
Viewed 80 times
-1
-
Does this answer your question? [Redirect stdout to a file](https://stackoverflow.com/questions/29154056/redirect-stdout-to-a-file) – Claudio Sep 04 '22 at 10:52
1 Answers
1
I have written for my own purposes following function:
def stdoutOf(strToExec):
import io, sys; ioS = io.StringIO() # create file like string
stdout = sys.stdout # save sys.stdout to restore it later on
sys.stdout = ioS # redirect stdout to the string
exec(strToExec) # some code to run with stdout written to a string
sys.stdout = stdout # restore sys.stdout
ioS.seek(0)
return ioS.read() # get what was written to stdout
#:stdout_of()
from which you can take the code if you need to process the error messages before writing them to the file or use the method described here Redirect stdout to a file in Python? and nailed down to with open(‘filename.ext’, ‘w’) as sys.stdout:
as your question has already an answer on stackoverflow.

Claudio
- 7,474
- 3
- 18
- 48