您好,登錄后才能下訂單哦!
怎么避免不能區(qū)分py2和py3?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
不能區(qū)分Python 2和Python 3
看下面這個(gè)文件foo.py:
import sys def bar(i): if i == 1: raise KeyError(1) if i == 2: raise ValueError(2) def bad(): e = None try: bar(int(sys.argv[1])) except KeyError as e: print('key error') except ValueError as e: print('value error') print(e) bad()
在Python 2里,運(yùn)行起來沒有問題:
$ python foo.py 1 key error 1 $ python foo.py 2 value error 2
但是如果拿到Python 3上面玩玩:
$ python3 foo.py 1 key error Traceback (most recent call last): File "foo.py", line 19, in <module> bad() File "foo.py", line 17, in bad print(e) UnboundLocalError: local variable 'e' referenced before assignment
這是怎么回事?“問題”在于,在Python 3里,在except塊的作用域以外,異常對(duì)象(exception object)是不能被訪問的。(原因在于,如果不這樣的話,Python會(huì)在內(nèi)存的堆棧里保持一個(gè)引用鏈直到Python的垃圾處理將這些引用從內(nèi)存中清除掉。更多的技術(shù)細(xì)節(jié)可以參考這里。)
避免這樣的問題可以這樣做:保持在execpt塊作用域以外對(duì)異常對(duì)象的引用,這樣是可以訪問的。下面是用這個(gè)辦法對(duì)之前的例子做的改動(dòng),這樣在Python 2和Python 3里面都運(yùn)行都沒有問題。
import sys def bar(i): if i == 1: raise KeyError(1) if i == 2: raise ValueError(2) def good(): exception = None try: bar(int(sys.argv[1])) except KeyError as e: exception = e print('key error') except ValueError as e: exception = e print('value error') print(exception) good()
在Py3k里面運(yùn)行:
$ python3 foo.py 1 key error 1 $ python3 foo.py 2 value error 2
關(guān)于怎么避免不能區(qū)分py2和py3問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。