1

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.

3
  • you want to use print to store it to variable instead of displaying it to console??? Commented Feb 18, 2015 at 18:36
  • 1
    You want to redirect stdout. See this post stackoverflow.com/questions/1218933/… Commented Feb 18, 2015 at 18:36
  • you can also just use a normal file and seek before printing without needing an import Commented Feb 18, 2015 at 19:30

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I missed the "answer your own question" checkbox, my bad.
printing a would print StringIO.StringIO instance at ...
0

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>
>>> 

Comments

0

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. Use file.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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.