How to redefine stderr out and stdout out to separately logs files using logging module ? For example stderr.log and stdout.log files ?
Asked
Active
Viewed 813 times
2 Answers
8
You can simply replace sys.stdout
and sys.stderr
with custom file-like objects:
import sys
sys.stdout = open('stdout.log', 'a')
sys.stderr = open('stderr.log', 'a')
To undo:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
For more information, read the sys
module documentation.

Ferdinand Beyer
- 64,979
- 15
- 154
- 145
1
import sys
class OutDevice():
def write(self, s):
# do whatever
pass
class ErrDevice():
def write(self, s):
# do whatever
pass
sys.stdout = OutDevice()
sys.stdout = ErrDevice()
# to restore
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

Sid
- 7,511
- 2
- 28
- 41