-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterceptPrintC.py
More file actions
53 lines (41 loc) · 1.46 KB
/
InterceptPrintC.py
File metadata and controls
53 lines (41 loc) · 1.46 KB
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
#-------------------------------------------------------------------------------
# Name: InterceptPrintM
# Purpose: A class to allow Python 2.7's print function to be intercepted and augmented
#
# Author: Simon Cox
#
# Created: 19/10/2015
# Copyright: (c) Simon Cox 2015
# Licence: Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
#-------------------------------------------------------------------------------
import traceback
import sys
import datetime
class InterceptPrint(object):
def __init__(self, linenumber=False, timestamp=False):
self.realstdout = sys.stdout
sys.stdout = self
self.linenumber = linenumber
self.timestamp = timestamp
def write(self, message):
prepends = []
if self.linenumber:
prepends.append('Line number: ' + str(traceback.extract_stack()[-2][1]))
if self.timestamp:
prepends.append('Datetime: ' + datetime.datetime.now().isoformat())
if prepends:
prependstring = ' '.join(prepends) + ' '
else:
prependstring =''
if message == '\n' or message == ' ':
return
sys.stdout = self.realstdout
print prependstring + message
sys.stdout = self
if __name__ == '__main__':
ip = InterceptPrint(linenumber=True)
for i in range(0,100):
print i, 'hello'
ip.timestamp = True
for i in range(0,100):
print i, 'bob'