Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "print >>" do in python? [duplicate]

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, '--'
like image 668
Sebastian Avatar asked Dec 20 '15 20:12

Sebastian


People also ask

What << means in Python?

They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.

What is the name of >> operator in Python?

In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand.

Is it += or =+ in Python?

The Python += operator lets you add two values together and assign the resultant value to a variable. This operator is often referred to as the addition assignment operator. It is shorter than adding two numbers together and then assigning the resulting value using both a + and an = sign separately.


3 Answers

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)
like image 160
Eugene Yarmash Avatar answered Oct 23 '22 01:10

Eugene Yarmash


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

print >>sys.stderr, 'Hello'

to:

print('Hello', file=sys.stderr)
like image 21
Tom Karzes Avatar answered Oct 23 '22 02:10

Tom Karzes


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")
like image 3
elm Avatar answered Oct 23 '22 02:10

elm