Python 3 operator>>打印到fi

2024-05-19 15:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下Python代码来编写项目的依赖文件。它在Python2.x上运行良好,但是在Python3上测试时报告了一个错误。

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'

使用Python2.x和3.x最好的方法是什么?


Tags: 文件项目代码noneif报告错误not
3条回答

请注意,从Python3.6.3(2017年9月)开始,本例的错误消息将更改为建议使用Python3拼写:

>>> 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>)"?

(添加了显式换行符以避免侧滚-实际错误消息仅在终端窗口的宽度处换行)

^{}是Python 3中的一个函数。

将代码更改为print(s, end="", file=depend)or let the ^{} tool do it for you.

在Python 3中,print语句已成为一个函数。新语法如下:

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

Python 3中的这种突破性变化意味着在使用print语句/函数写入文件时,不可能在Python 2和python3中使用相同的代码。一种可能的选择是使用depend.write(s)而不是打印。

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

相关问题 更多 >