5

I want to redirect all the output, even from the external modules which are imported to a file.

sys.stdout = open('logfile', 'a')

doesn't do the job for the logging done by external files is echoed on stdout.

I've tinkered with the source code of external modules, and they are deeply knitted with python's "logging" module and rely on it for the output.

Also, I don't want to use stream redirection using > operator.

2 Answers 2

4
import sys

sys.stdout = sys.stderr = open('logfile', 'a')

print('this should be working from anywhere')
import logging
logging.warn('this too')

The reasson you saw external modules print to console was probably that they were using stderr (which is the default output handler for the logging module).

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

sysstdout = sys.stdout
log_file = open("your_log_file.txt","w")
sys.stdout = log_file
print("this will be written to message.log")
sys.stdout = sysstdout
log_file.close()

Or, do the right thing and use Python's logging module properly.

1 Comment

Nope, it doesn't redirect external modules imported. External modules seem to do things in their own way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.