使Python 2.7代码与Python 2.6一起运行 [英] Making Python 2.7 code run with 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 / horizon / + 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屋!