-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.py
74 lines (61 loc) · 2.12 KB
/
logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# @file mflib/logger.py
# @author Michael Foukarakis
# @version 0.1
# @date Created: Tue Jan 27, 2015 18:19 EET
# Last Update: Mon Oct 30, 2017 10:54 CET
#------------------------------------------------------------------------
# Description: Useful constructs for logging
#------------------------------------------------------------------------
# History: <+history+>
# TODO: <+missing features+>
#------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------
import sys
class duplicate_stdout():
"""Context manager for temporarily duplicating stdout to a file. Like tee, but limited in scope.
# How to duplicate help() to 'help.txt':
with duplicate_stdout('help.txt', 'w'):
help(ord)
Not reusable, and not reentrant.
"""
def __init__(self, path, mode):
self.path = path
self.mode = mode
self.stdout = sys.stdout
def __enter__(self):
self.fh = open(self.path, self.mode)
return self
def __exit__(self, *args):
sys.stdout = self.stdout
self.fh.flush()
self.fh.close()
def write(self, buffer):
self.fh.write(buffer)
self.stdout.write(buffer)
def flush(self):
self.fh.flush()
class duplicate_stderr():
"""Context manager for temporarily duplicating stderr to a file. Like tee, but limited in scope.
# How to duplicate sys.stderr.write to 'help.txt':
with duplicate_stderr('help.txt', 'w'):
sys.stderr.write(help(ord))
Not reusable, and not reentrant.
"""
def __init__(self, path, mode):
self.path = path
self.mode = mode
self.stderr = sys.stderr
def __enter__(self):
self.fh = open(self.path, self.mode)
return self
def __exit__(self, *args):
sys.stderr = self.stderr
self.fh.flush()
self.fh.close()
def write(self, buffer):
self.fh.write(buffer)
self.stderr.write(buffer)
def flush(self):
self.fh.flush()