#!/usr/bin/python ### ### Copyright (C) 1998-2010 by the Free Software Foundation, Inc. ### ### This program is free software; you can redistribute it and/or ### modify it under the terms of the GNU General Public License ### as published by the Free Software Foundation; either version 2 ### of the License, or (at your option) any later version. ### ### This program is distributed in the hope that it will be useful, ### but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### ### You should have received a copy of the GNU General Public License ### along with this program; if not, write to the Free Software ### Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ### 02110-1301, USA. http://www.fsf.org/licensing/licenses/gpl.html ### ### --------------------------- ### ### This object may be used to capture output that would have gone to ### STDOUT (or STDERR). It's based on the fact that (according to ### Python docs), "stdout and stderr needn't be built-in file ### objects: any object is acceptable as long as it has a write() ### method that takes a string argument." ### ### If you wanted to redirect sys.stdout to nothing, you could do: ### ### class NullStream: ### def write(self, text): pass ### sys.stdout = NullStream() ### ### But this class allows you to capture what would have otherwise ### gone to STDOUT into a list, and then retrieve it later for ### analysis. ### ### This is useful when doing unit tests because it allows you to ### capture what would have gone to STDOUT and check it for certain ### things, without having stuff actually go to STDOUT and mess up ### the unit test output. ### ### It can be used like: ### ### mylist = ListSream() ### sys.stdout = mylist ### test_method_that_prints() # no output! ### mylist.clear() # optional, only if plan to use again ### sys.stdout = sys.__stdout__ # restore regular output ### found = False ### for line in mylist.contents(): ### if (re.search('looking_for', line)): ### found = True ### break ### if (found): print 'looking_for was found in output!' ### ### Author: Anthony R. Thompson ### Contact: put @ between art and sigilservices.com ### Created: Nov 2009 ### class ListStream: def __init__(self): self.mysavelist = [] def write(self, text): self.mysavelist.append(text) def clear(self): self.mysavelist = [] def contents(self): return self.mysavelist def readlines(self): return self.mysavelist if __name__ == '__main__': pass