【问题标题】:How do I have "print" calls such that code works bot in Python 2 and Python 3? [duplicate]如何进行“打印”调用,以便代码在 Python 2 和 Python 3 中运行? [复制]
【发布时间】: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


【解决方案1】:

print是python2.7中的一个关键字,它会接受一个元组作为下一段语法,使它看起来像一个函数调用:

Python 2.7.3 (default, Jun 21 2016, 18:38:19) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hi'
hi
>>> print("hi")
hi

如果您使用字符串元组,这可能会产生误导,例如:

>>> print("hello", "world")
('hello', 'world')

最好的办法是使用导入告诉解释器用函数调用替换关键字:from __future__ import print_function

>>> from __future__ import print_function
>>> print("hi!")
hi!
>>> print "hi"
  File "<stdin>", line 1
    print "hi"
             ^
SyntaxError: invalid syntax
>>> print("hello", "world")
hello world

【讨论】:

  • 我认为导入print_function唯一确保两者兼容的方法。
  • 否定。在 python2 中,print 是一个语句,而不是一个函数。 print("hi") 评估为 print ("hi")。括号在该声明中没有任何作用。如果你尝试 `print("Hello", "world"),你会看到这个,它打印出一个元组,而不是一个字符串
  • 是的,你是对的。这种区别很重要,它使未来的进口更加重要。我会更新我的答案。
【解决方案2】:

您在考虑版本控制方面有正确的想法。但是,python 并没有按照您的想法进行解释。代码首先被编译成字节码,然后运行(与 PERL 不同)。这就是为什么你不能编写一个无限的while循环并实时编辑它并期望它改变你看到的输出。

因此,您的语法仍然必须与 python3 兼容,即使在 python2 部分的代码中也是如此。

解决此问题的一种方法是从__future__ 导入print_function。为此,将以下行添加到 Python 脚本的顶部:

if sys.version_info[0] < 3:
    from __future__ import print_function

...然后只需在代码的 python2 部分中使用 python3 的 print(...)

【讨论】:

    【解决方案3】:

    您可以在检测到 Python 2.* 时有条件地from __future__ import print_function

    if sys.version_info[0] < 3:
        from __future__ import print_function
    

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 2013-04-01
      • 2014-11-29
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多