Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:“中不支持的操作数类型”;打印>>&引用;陈述_Python_Python 3.x_Printing_Python 2.x_Python 3.6 - Fatal编程技术网

Python TypeError:“中不支持的操作数类型”;打印>>&引用;陈述

Python TypeError:“中不支持的操作数类型”;打印>>&引用;陈述,python,python-3.x,printing,python-2.x,python-3.6,Python,Python 3.x,Printing,Python 2.x,Python 3.6,当我尝试在Python 3.6下运行此代码时: import sys print >>sys.stderr, 'waiting for a connection' 我得到这个TypeError: Traceback (most recent call last): File "D:/Users/Chanhc1997/Desktop/test_c.py", line 8, in <module> print >>sys.stderr, 'wait

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

import sys

print >>sys.stderr, 'waiting for a connection'
我得到这个
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>)"?
回溯(最近一次呼叫最后一次):
文件“D:/Users/Chanhc1997/Desktop/test_c.py”,第8行,在
打印>>sys.stderr,“正在等待连接”
TypeError:不支持>>的操作数类型:
“内置函数”或“方法”和“伪输出文件”。
你是说“打印(,文件=)”吗?
该代码在Python 2中运行良好。发生了什么事?

在Python 2中,这是:

print >>sys.stderr, 'waiting for a connection'
表示“将字符串
“等待连接”
打印到类似对象的文件
sys.stderr

在Python 3中,将变成一个而不是一个语句,重定向其输出的语法如下所示:

print('waiting for a connection', file=sys.stderr)
在Python3中会出现
TypeError
(而不是
SyntaxError
),因为现在
print
是一个函数(因此也是一个对象),它可以是表达式的一部分……而且因为
>
是一个运算符,表达式片段

print >>sys.stderr
被解释为“按
sys.stderr
位右边的
print
函数”-这在语法上是有效的,但对这些对象没有任何意义

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

from __future__ import print_function  # works in Python 2.6 and onwards

print('whatever', file=some_file)

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

错误消息中包含您问题的答案:在使用Python 3时,您必须使用
print(TEXT,file=sys.stderr)
而不是
sys.stderr,TEXT
。谢谢,它起作用了!但是我想知道为什么同样的代码可以在openwrt(linkit 7688 duo,python支持)上工作,而在python-3.6编译器上,我们需要在编译之前修改print()部分??