使Python 2.7代码与Python 2.6一起运行 [英] Making Python 2.7 code run with Python 2.6

查看:147
本文介绍了使Python 2.7代码与Python 2.6一起运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的python函数,可以提取一个zip文件(与平台无关)

I have this simply python function that can extract a zip file (platform independent)

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上运行失败:

This runs fine with Python 2.7 but fails with Python 2.6:

AttributeError: ZipFile instance has no attribute '__exit__':

我发现此建议要求升级2.6-> 2.7
https://bugs.launchpad。 net / horizo​​n / + bug / 955994

I found this suggestions that an upgrade is required 2.6 -> 2.7 https://bugs.launchpad.net/horizon/+bug/955994

但是是否可以将上面的代码移植到Python 2.6上并仍然跨平台使用?

But is it possible to port the above code to work with Python 2.6 and still keep it cross platform?

推荐答案

有关:

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 确实执行<$ c上缺少的 __ exit __ 方法的作用$ c> ZipFile 应该可以。即,调用 close 方法

contextlib.closing does exactly what the missing __exit__ method on the ZipFile would be supposed to do. Namely, call the close method

这篇关于使Python 2.7代码与Python 2.6一起运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆