-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathlog.py
More file actions
executable file
·36 lines (29 loc) · 831 Bytes
/
log.py
File metadata and controls
executable file
·36 lines (29 loc) · 831 Bytes
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
#!/usr/bin/env python
from contextlib import contextmanager
"""
This changes the print-function, such that all output is also copied to a log file
"""
@contextmanager
def print_to_file(filename):
import sys
old_stdout = sys.stdout
try:
logfile = open(filename, "w")
except:
yield
class CustomPrint():
def __init__(self, stdout, logfile):
self.old_stdout = stdout
self.logfile = logfile
def write(self, text):
self.old_stdout.write(text)
self.logfile.write(text)
def flush(self):
self.old_stdout.flush()
self.logfile.flush()
sys.stdout = CustomPrint(old_stdout, logfile)
sys.stderr = CustomPrint(old_stdout, logfile)
try:
yield
finally:
sys.stdout = old_stdout