When I try to run this code under Python 3.6:
import sys
print >>sys.stderr, 'waiting for a connection'
I get this TypeError:
Traceback (most recent call last):
File "D:/Users/Chanhc1997/Desktop/test_c.py", line 8, in <module>
print >>sys.stderr, 'waiting for a connection'
TypeError: unsupported operand type(s) for >>:
'builtin_function_or_method' and 'PseudoOutputFile'.
Did you mean "print(<message>, file=<output_stream>)"?
The code works fine in Python 2. What's going on?
In Python 2, this:
print >>sys.stderr, 'waiting for a connection'
means "print the string 'waiting for a connection' to the file-like object sys.stderr".
In Python 3, print becomes a function rather than a statement, and the syntax to redirect its output looks like this:
print('waiting for a connection', file=sys.stderr)
You get a TypeError (rather than, say, a SyntaxError) in Python 3 because, now that print is a function (and therefore an object), it can be part of an expression … and since >> is an operator, the expression fragment
print >>sys.stderr
is interpreted as "shift the print function right by sys.stderr bits" – which is syntactically valid, but doesn't make any sense for those objects.
If you need to write code which runs under both Python 2 and Python 3, you can import Python 3's behaviour into Python 2:
from __future__ import print_function # works in Python 2.6 and onwards
print('whatever', file=some_file)
Note that this will disable the ability to treat print as a statement, so you'll have to update any code which uses that behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With