Reputation: 7385
I would like some way to print()
to a string or internal buffer rather than stdout in Python.
Ideally, I could print to this and later dump the string to the console just as if it had been printed to stdout to begin with. Something like:
>>> print("output 1", a)
>>> print("output 2", a)
>>> print(a)
output 1
output 2
If you're wondering, I'm doing this for the sake of quick refactoring on code that previously printed directly to the console.
Upvotes: 1
Views: 561
Reputation: 148880
What you are looking for is the StringIO module.
You simply use it that way :
import StringIO
a= StringIO.StringIO()
a.write('output 1\n')
print >>a, 'output 2'
# Retrieve file contents -- this will be
# 'output 1\noutput 2\n'
contents = a.getvalue()
# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
a.close()
# will output 'output 1\noutput 2\n'
print contents
EDIT : I had not seen Josh's answer before posting mine. His syntax is for python 3 mine is for older python 2.x
Upvotes: 1
Reputation: 9075
In general, the print()
method takes a seldom-used parameter, file
, which simply has to be a 'file-like' (it defaults to stdout). From the doc:
The file argument must be an object with a
write(string)
method; if it is not present or None, sys.stdout will be used. Output buffering is determined by file. Usefile.flush()
to ensure, for instance, immediate appearance on a screen.
You could provide your own buffering implementation or use StringIO
as the file-like if you wanted to maintain the print
syntax.
Upvotes: 0
Reputation: 7385
StringIO
acts like a virtual file and can be used for this purpose, but you must be careful to get the behavior you described:
>>> import io
>>> a = io.StringIO('')
>>> print("output 1", file=a)
>>> print("output 2", file=a)
>>> print(a.getvalue()) # notice the extra new line at the end...
output 1
output 2
>>> print(a.getvalue(), end='') # use end='' to suppress extra new line
output 1
output 2
>>> print(a) # print(a) will not yield the same results
<_io.StringIO object at 0x7fe3a23568b8>
>>> print("output 3", a) # make sure to use "file=", or it will print str(a)!
output 3 <_io.StringIO object at 0x7fe3a23568b8>
>>>
Upvotes: 0