Python 3中的操作符>>用于将内容打印到文件

33
我有以下Python代码用于编写项目的依赖文件。它在Python 2.x下运行正常,但在使用Python 3测试时报告了一个错误。
depend = None
if not nmake:
    depend = open(".depend", "a")
dependmak = open(".depend.mak", "a")
depend = open(".depend", "a")
print >>depend, s,

这里是错误信息:

Traceback (most recent call last):
  File "../../../../config/makedepend.py", line 121, in <module>
    print >>depend, s,
    TypeError: unsupported operand type(s) for >>:
      'builtin_function_or_method' and '_io.TextIOWrapper'

如何以最佳方式在Python 2.x和3.x中使其工作?


“使用Python2.x和3.x”?你不能在两个版本中都有相同的代码。通常,你可以使用“2to3”工具将Python 2的代码转换为Python 3。 - S.Lott
3
您可以使用 from __future__ import print_function 将 Python 3 的 print() 函数导入 Python 2 中。另请参阅 http://python3porting.com。 - Lennart Regebro
4个回答

47

在Python 3中,打印语句已经变成了一个函数。新的语法看起来像这样:

print(s, end="", file=depend)

在Python 3中的这个重大变化意味着,当使用print语句/函数写入文件时,无法在Python 2和3中使用相同的代码。一个可能的选择是使用depend.write(s)而不是print。

更新:J.F.Sebastian正确指出,您可以在Python 2代码中使用from __future__ import print_function来启用Python 3语法。这将是跨不同Python版本使用相同代码的绝佳方法。


3
你可以使用 from __future__ import print_function 在 Python 2.x 中使用 print() 函数。另外,end="" 和在 print 语句中使用逗号不同。请比较 print'a',;print'b'print('a',end=''); print('b')(注意:后一种情况下 ab 之间没有空格)。 - jfs

12

3
请注意,从Python 3.6.3(2017年9月)开始,对于此情况的错误消息将更改为建议使用Python 3的拼写方式。
>>> print >> sys.stderr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>:
    'builtin_function_or_method' and '_io.TextIOWrapper'.
    Did you mean "print(<message>, file=<output_stream>)"?

(为避免出现横向滚动条,已添加显式换行符 - 实际的错误消息只会在终端窗口的宽度处换行。)

0
我可以提出至少两种方法。
1 - if-else 方法与 eval() 技巧(适用于标准输出和文件)。
import sys
def println(s, f=sys.stdout):
    if sys.version_info[0] < 3:
        print >>f, s
    else:
        func = eval('print')
        func(s, end='\n', file=f)

f = open('file.txt', 'a')
println('msg') # print to stdout
println('msg', f) # print to file
f.close()

2 - 使用 write() 而非 print()。

f = open('file.txt', 'a')
f.write("%s\n" % 'msg')
f.close()

在 Python 2.7.17 和 3.6.9 上测试了这两个脚本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接