2
import cStringIO

output = cStringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

What does >>output in the print statement on line 5 do?

Mattie
  • 20,280
  • 7
  • 36
  • 54
Deck Trout
  • 161
  • 11

1 Answers1

6

It redirects the print statement output to an open file-like object. See the print statement documentation:

print also has an extended form, defined by the second portion of the syntax described above. This form is sometimes referred to as “print chevron.” In this form, the first expression after the >> must evaluate to a “file-like” object, specifically an object that has a write() method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates to None, then sys.stdout is used as the file for output.

Essentially, the line is translated to output.write('Second line.' + '\n') asprint` adds a newline to it's output unless the expression ends with a comma.

The syntax is based on the bash append >> syntax (which also influenced C++ << and >> I/O operators); see PEP 214 for a full motivation for why this was chosen.

In Python 3, where print() is a function, you'd write:

print('Second line.', file=output)

instead.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I removed the sentence on possible origins of the syntax to prevent any possible misinformation spread. I highly doubt that it's true; the doc doesn't mention that, [citation needed]. – ulidtko Jun 13 '13 at 14:21
  • @ulidtko: And why do you doubt that it is true or misinformation? C++ certainly has that syntax. – Martijn Pieters Jun 13 '13 at 14:23
  • @ulidtko: I'll refine it; motivations for the syntax are documented in [PEP 214](http://www.python.org/dev/peps/pep-0214/). – Martijn Pieters Jun 13 '13 at 14:26
  • Because 1) in C++ `stream >> var` means **input**; 2) output is `stream << "value"`; 3) it isn't in any way redirection. – ulidtko Jun 13 '13 at 14:27
  • @ulidtko: The PEP mentions that, yes. In future, I'd appreciate a comment; I'm quite happy to discuss things and fix things if (as usual) it turns out I was wrong once more. – Martijn Pieters Jun 13 '13 at 14:29
  • Ok, current version is better. I'd edit immediately rather than ask for correction in comments for a pretty simple reason: comments can be ignored and forgotten, while edits stay until fixed or refined. – ulidtko Jun 13 '13 at 14:31