【发布时间】:2018-01-09 22:27:26
【问题描述】:
我正在尝试更改 Python 2.7 代码,使其可以在 2.7 和 3.6 上运行。明显的问题是 print。在 2.7 中不带括号调用,在 3.6 中带括号调用所以我尝试了运行时版本检测(检测代码取自 this answer):
def customPrint(line):
if sys.version_info[0] < 3:
print "%s" % line
else:
print( line )
当我在 Python 3.6 下运行它时,我收到一条错误消息说
语法错误:调用“打印”时缺少括号
很明显,Python 试图解释所有代码。这与 PHP 不同。
我如何拥有 print 的这种自定义实现,它使用来自 Python 2 或来自 Python 3 的 print,具体取决于它的运行位置?
【问题讨论】:
-
我认为你可以有条件地
from __future__ import print_function检测到 Python 2.*。
标签: python python-2.7 python-3.x