【问题标题】:Making Python 2.7 code run with Python 2.6使 Python 2.7 代码与 Python 2.6 一起运行
【发布时间】:2014-02-11 15:46:45
【问题描述】:

我有这个简单的 python 函数,可以提取一个 zip 文件(独立于平台)

def unzip(source, target):
    with zipfile.ZipFile(source , "r") as z:
        z.extractall(target)
    print "Extracted : " + source +  " to: " + target

这在 Python 2.7 上运行良好,但在 Python 2.6 上运行失败:

AttributeError: ZipFile instance has no attribute '__exit__':

我发现这个建议需要升级 2.6 -> 2.7 https://bugs.launchpad.net/horizon/+bug/955994

但是是否可以将上述代码移植到 Python 2.6 并仍然保持跨平台?

【问题讨论】:

    标签: python python-2.7 compatibility python-2.6


    【解决方案1】:

    怎么样:

    import contextlib
    
    def unzip(source, target):
        with contextlib.closing(zipfile.ZipFile(source , "r")) as z:
            z.extractall(target)
        print "Extracted : " + source +  " to: " + target
    

    contextlib.closing 正是 ZipFile 上缺少的 __exit__ 方法应该做的事情。即调用close方法

    【讨论】:

    【解决方案2】:

    zipfile 模块在 python 版本 2.7.1 中更改:

    • 如果文件是使用模式“a”或“w”创建的,然后关闭时没有 将任何文件添加到存档,适当的 ZIP 结构 将向文件写入一个空存档。
    • ZipFile 也是一个上下文管理器,因此支持 with 声明。

    我通过不为 python 2.6 使用上下文管理器“with”解决了同样的问题

     newzip = None
     try:
         newzip =  zipfile.ZipFile(_file + ".zip", "w", zipfile.ZIP_DEFLATED)
         newzip.write(_file)
     finally:
         newzip.close()
    

    with 上下文管理器可防止资源泄漏,因此在 Python 2.6 中,我至少仍会建议使用 try/finally 来关闭资源。

    【讨论】:

    • with 上下文管理器可以防止资源泄漏,所以在 Python 2.6 中我至少仍然建议尝试/最终关闭资源。
    猜你喜欢
    • 2018-04-21
    • 2017-01-17
    • 2015-01-18
    • 2014-05-26
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 2013-04-11
    • 2013-11-28
    相关资源
    最近更新 更多