【发布时间】:2018-05-16 02:06:11
【问题描述】:
我手头有一个简单的任务...处理异常,以便在 python2.x/3.x 之间使用 urllib/urllib2 时代码不会抛出 IncompleteRead
python2
try:
page = urllib2.urlopen(urls).read()
except httplib.IncompleteRead, e:
page = e.partial
python3
try:
page = request.urlopen(urls).read()
except (http.client.IncompleteRead) as e:
page = e.partial
现在由于模块本身不同,如何进行尝试,除非我不知道我的用户将运行哪个 python 版本?
我也无法在我的 try-except 中检查 python 版本...或者我可以吗?
有没有办法捕捉它的超类,所以它对于两个 python 版本都一样?如果是,怎么做?
【问题讨论】:
-
可能是更好的方法,但您可以使用
sys.version检查哪个版本的python正在运行您的脚本 -
好的...但是一旦我得到版本,我该如何处理异常?我的代码中只有一个 try-except 块...
-
除非您需要 Python 2.5,否则您可以在 2.x 中使用新式
except:语句。
标签: python python-3.x python-2.7 exception-handling