【问题标题】:Should I trust "python -3" as returning an exhaustive result?我应该相信“python -3”返回详尽的结果吗?
【发布时间】:2016-07-09 00:50:40
【问题描述】:

正如您在“man python”中所读到的:

-3 警告 Python 3.x 2to3 无法轻松修复的不兼容性。

这个命令已经帮助我过去避免不兼容 Python 2.x 和 3.x 的代码。

但是,我对this 代码没有任何警告。 我应该相信“python -3”会返回详尽的结果吗?

注意:令人惊讶的是,here 没有提及此选项。

【问题讨论】:

  • 因为该代码与 3.x 并非不兼容。除非你的意思是使用__nonzero__?在这种情况下,可能是因为它正在寻找“2to3 无法轻松修复的不兼容性”,而这是一个非常简单的修复。不清楚你在说什么代码。
  • 您的链接指向 Python 3 文档。 Python 3 没有那个标志。 (令人惊讶的是,Python 2 documentation 没有提到 2to3 警告。)
  • @user2357112 -- 是的,我也对此感到惊讶(这就是为什么我最初的答案有 2to3 可以轻松处理的代码)。
  • 我在文档中添加了bug。谁知道在他们修复它之前需要多长时间(或者如果他们这样做了)......但至少它在那里......

标签: python compatibility


【解决方案1】:

不,您不应将该警告视为详尽无遗。以下代码在 python2.x 和 python3.x 上的行为不同,但不会发出警告:

from __future__ import print_function

class test(object):
    def __nonzero__(self):
        return False

t = test()
if t:
    print('Hello')

(至少不是 OSX 上的 python2.7.10)。好的,也许这段代码可以由 2to3 处理(它是)——尽管我仍然希望基于official documentation 的警告。

通过针对 Python 3 中已删除或显着更改的功能发出 DeprecationWarning 来警告 Python 3.x 可能存在的不兼容性。

下面是一些代码示例,isn't handled by 2to3 使用 -3 选项仍然没有发出警告:

from __future__ import print_function

import subprocess

class Pipe(object):
    def __init__(self,openstr):
        self.gnu_process=subprocess.Popen(openstr.split(),
                                          stdin=subprocess.PIPE)

    def put_in_pipe(self,mystr):
        print(mystr, file=self.gnu_process.stdin)

if __name__=="__main__":
    print("This simple program just echoes what you say (control-d to exit)")
    p = Pipe("cat -")
    while True:
        try:
            inpt = raw_input()
        except EOFError:
            break
        print('putting in pipe:%s' % inpt)
        p.put_in_pipe(inpt)

这段代码的问题在于,在 python3 中,我的管道需要一个字节对象,但它得到了一个 str(python2.x 的 unicode)。

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 2023-03-17
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2015-12-23
    • 2012-05-01
    • 2013-08-30
    • 1970-01-01
    相关资源
    最近更新 更多