47

I have to translate a code from python 2 into python 3 and I can't understand what does print >> do and how should I write it in python 3.

print >> sys.stderr, '--'
print >> sys.stderr, 'entrada1: ', entrada1
print >> sys.stderr, 'entrada2: ', entrada2
print >> sys.stderr, '--'
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Sebastian
  • 573
  • 1
  • 5
  • 14

3 Answers3

50

The >> sys.stderr part makes the print statement output to stderr instead of stdout in Python 2.

To quote the 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.

In Python 3 use the file argument to the print() function:

 print("spam", file=sys.stderr)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
23

To convert these from Python 2 to Python 3, change:

print >>sys.stderr, 'Hello'

to:

print('Hello', file=sys.stderr)
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
4

For printing to stderr note

sys.stderr.write()

is portable across versions, yet you need to add a newline, unlike print; for instance

import sys

errlog = sys.stderr.write
errlog("an error message\n")
elm
  • 20,117
  • 14
  • 67
  • 113
  • 3
    Also note that [`.write()`](https://docs.python.org/2/library/stdtypes.html#file.write) expects its argument to be a string. To write something other than a string, it needs to be converted to a string first: `sys.stderr.write(str(['the answer', 42]))` – Eugene Yarmash Dec 20 '15 at 22:45