[python] StriingIO module
StringIO is usually used for buffer of string. which can have stdin,stdout,stderr redirected to a buffer.
this moudle contains all of below methods.
f = StringIO() # ready for writing
f = StringIO(buf) # ready for reading
f.close() # explicitly release resources held
flag = f.isatty() # always false
pos = f.tell() # get current position
f.seek(pos) # set current position
f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
buf = f.read() # read until EOF
buf = f.read(n) # read up to n bytes
buf = f.readline() # read until end of line ('\n') or EOF
list = f.readlines()# list of f.readline() results until EOF
f.truncate([size]) # truncate file at to at most size (default: current pos)
f.write(buf) # write at current position
f.writelines(list) # for line in list: f.write(line)
f.getvalue() # return whole file's contents as a string
1.write into buffer
1 from StringIO import StringIO 2 file = StringIO() 3 file.write('do something') 4 file.write('do anything') 5 print file.getvalue() 6 file.close() 7 8 #do somethingdo anything
2.re-direct
1 '''Write into buff, not file''' 2 from StringIO import StringIO 3 import sys 4 #save the original status so that restore once re-direct behavior is complete. 5 stdout = sys.stdout 6 buff = StringIO() 7 #re-direct sys.stdout to buff object. 8 sys.stdout = buff #two of them have write() method. 9 #anything doing will re-direct into buffer, instead of sys.stdout. 10 print 'do something, do anything' 11 #copy stdout into variable contents 12 contents = buff.getvalue() 13 #re-assign the default value to sys.stdout 14 sys.stdout = stdout 15 print contents 16 17 18 # an simple and concise method 19 print >> buff,'code analysis' 20 print buff.getvalue() 21 22 ##with output being 23 ##do something, do anything 24 ## 25 ##do something, do anything 26 ##code analysis
3.customize buff object
1 import sys 2 from StringIO import StringIO 3 ''' this class customized by user need to have write() method''' 4 class Buffer(): 5 def __init__(self): 6 self.out = sys.stdout 7 self.log = StringIO() 8 def write(self, text): 9 self.log.write(text) 10 #self.out.write(text) 11 12 #store the original status so that restore once re-direct behavior is complete 13 stdout = sys.stdout 14 # Create an instance of the user-defined output buffer to capture the output 15 buffout = Buffer() 16 # copy the buffer obj into sys.stdout 17 sys.stdout = buffout 18 print 'do something, do anything' 19 # Copy stdout into variable(contents) 20 contents = buffout.log.getvalue() 21 #restore the original status 22 sys.stdout = stdout 23 print contents 24 25 #### do something, do anything
4. customize buff object (con't)
1 import sys 2 3 #Define an I/O object 4 class StdoutToStr: 5 def __init__(self): 6 self.buffer = '' 7 def write(self, buf): 8 self.buffer += buf 9 10 #Re-direct standard output 11 temp = sys.stdout 12 output = StdoutToStr() 13 14 sys.stdout = output 15 print "do something" 16 print "do anything" 17 print "do everything" 18 19 sys.stdout = temp 20 print output.buffer 21 22 23 ##do something 24 ##do anything 25 ##do everything
5. Customize buff object appending clear method(con't) captureoutput.py
1 #!/usr/bin/env python 2 3 """ 4 This module is used to capture output sent to sys.stdout and make the output 5 available programmatically. 6 7 Usage: 8 import captureoutput 9 10 message = "Hello!" 11 try: 12 captureoutput.captureStdOut() 13 print(message) 14 finally: 15 captureoutput.uncaptureStdOut() 16 capturedText = captureoutput.getCapturedStdOut().rstrip() 17 print("Captured message is: %s"%captureText) 18 """ 19 #output Hello! 20 import sys 21 22 #//////////////////////////////////////////////////////////////////////////// 23 #//////////////////////////////////////////////////////////////////////////// 24 # Private attributes 25 #//////////////////////////////////////////////////////////////////////////// 26 #//////////////////////////////////////////////////////////////////////////// 27 28 # This class acts like an output file stream. Once assigned to sys.stdout, 29 # this class captures all output in a local attribute that can later be 30 # read back using the getvalue() method. 31 class _MyStringIO(object): 32 def __init__(self): 33 self.output = "" 34 35 def write(self, text): 36 self.output += text 37 38 def clear(self): 39 self.output = "" 40 41 def getvalue(self): 42 return self.output 43 44 _oldstdout = None 45 _localstdout = _MyStringIO() 46 47 #//////////////////////////////////////////////////////////////////////////// 48 #//////////////////////////////////////////////////////////////////////////// 49 # Public functions. 50 #//////////////////////////////////////////////////////////////////////////// 51 #//////////////////////////////////////////////////////////////////////////// 52 53 def captureStdOut(): 54 """Enables the capturing of standard output by hooking into sys.stdout. 55 Once hooked, all output sent to standard out is captured in a variable 56 that can be read using getCapturedStdOut(). 57 58 This function can be called more than once, the hook only occurs once 59 and subsequent calls are ignored. Call uncaptureStdOut() to restore 60 the old sys.stdout. 61 62 Note: The internal buffer is cleared when the sys.stdout is actually 63 hooked. 64 65 Note: Calls to this function cannot be nested. First call to this 66 function hooks sys.stdout. First call to uncaptureStdOut() unhooks 67 sys.stdout. 68 69 Arguments: 70 None. 71 72 Returns: 73 None. 74 """ 75 76 global _oldstdout 77 78 if _oldstdout is None: 79 _oldstdout = sys.stdout 80 sys.stdout = _localstdout 81 _localstdout.clear() 82 83 def uncaptureStdOut(): 84 """Disables the capturing of standard output. Any output that was 85 captured since getCaptureStdOut() was called is still available through 86 getCapturedStdOut(). 87 88 This function can be called more than once but only the first call 89 actually undoes the sys.stdout hook, subsequent calls are ignored. 90 91 Note: Calls to this function cannot be nested. First call to this 92 function unhooks sys.stdout. 93 94 Arguments: 95 None. 96 97 Returns: 98 None. 99 """ 100 101 global _oldstdout 102 103 if _oldstdout is not None: 104 sys.stdout = _oldstdout 105 _oldstdout = None 106 107 def getCapturedStdOut(): 108 """Retrieves whatever has been captured so far since getCaptureStdOut() 109 or clearCaptureStdOut() was called. 110 111 The captured data is cummulative. To reset the capture buffer, call 112 clearCapturedStdOut(). 113 114 Arguments: 115 None. 116 117 Returns: 118 A string containing all output sent to sys.stdout. 119 """ 120 121 return _localstdout.getvalue() 122 123 def clearCapturedStdOut(): 124 """Clears the internal buffer containing the captured output. 125 126 Arguments: 127 None. 128 129 Returns: 130 None. 131 """ 132 133 _localstdout.clear() 134 135 __all__ = ["captureStdOut", "uncaptureStdOut", "getCapturedStdOut" ]
6. Usage for captureoutput.py
1 import captureoutput as _captureoutput 2 _captureoutput.captureStdOut() 3 lines = None 4 try: 5 print ' hello\neveryone\n' 6 output = _captureoutput.getCapturedStdOut().rstrip() 7 lines = output.split('\r\n') 8 finally: 9 _captureoutput.uncaptureStdOut() 10 11 if lines: 12 for line in lines: 13 print line