类型错误:“print >> ...”语句中不支持的操作数类型

Qoo*_*Qoo 3 python printing python-2.x python-3.x python-3.6

当我尝试在 Python 3.6 下运行此代码时:

import sys

print >>sys.stderr, 'waiting for a connection'
Run Code Online (Sandbox Code Playgroud)

我明白了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>)"?
Run Code Online (Sandbox Code Playgroud)

该代码在 Python 2 中运行良好。这是怎么回事?

Zer*_*eus 5

在 Python 2 中,这样:

\n\n
print >>sys.stderr, \'waiting for a connection\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

意思是“将字符串打印\'waiting for a connection\'到类似文件的对象sys.stderr”。

\n\n

在 Python 3 中,print成为函数而不是语句,重定向其输出的语法如下所示:

\n\n
print(\'waiting for a connection\', file=sys.stderr)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 Python 3 中你会得到 a TypeError(而不是 a SyntaxError),因为现在它print是一个函数(因此也是一个对象),它可以是表达式 \xe2\x80\xa6 的一部分,并且因为它>>是一个运算符,所以表达式片段

\n\n
print >>sys.stderr\n
Run Code Online (Sandbox Code Playgroud)\n\n

被解释为“将函数右移位”\xe2\x80\x93,这在语法上是有效的,但对于这些对象没有任何意义。printsys.stderr

\n\n

如果您需要编写在 Python 2 和 Python 3 下运行的代码,您可以将 Python 3 的行为导入到 Python 2 中:

\n\n
from __future__ import print_function  # works in Python 2.6 and onwards\n\nprint(\'whatever\', file=some_file)\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,这将禁用视为语句的能力print,因此您必须更新使用该行为的任何代码。

\n