Python2轉(zhuǎn)Python3

前言

很早之前就知道python2官方快要不支持了,今年自己終于也要將python2寫的code逐步轉(zhuǎn)成python3,這里開始記錄一些轉(zhuǎn)移的筆記。

官方自帶工具轉(zhuǎn)換

$ 2to3  (按tab鍵自動(dòng)補(bǔ)全)
2to3      2to3-     2to3-2.7  2to3-3.7

這里我使用的是2to3-3.7將Python2.X代碼轉(zhuǎn)換成Python3.X

  • 轉(zhuǎn)換單個(gè)文件
$ 2to3-3.7 -w  1.py
  • 轉(zhuǎn)換文件夾下的文件
$ 2to3-3.7 -w  ./dir

補(bǔ)充說明:

  1. 以上命令建議只執(zhí)行一次,不要多次執(zhí)行。
  2. 這個(gè)工具只能解決大部分問題,部分代碼需要自己修改。

轉(zhuǎn)換成Python3一些記錄

    1. 如何兼容python2和python3代碼,根據(jù)版本來決定。

python3執(zhí)行

>>> import sys
>>> sys.version_info.major
3

python2執(zhí)行

>>> import sys
>>> sys.version_info.major
2
    1. 解決:UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position 32-33

使用Python的第三方庫requests發(fā)起post請(qǐng)求時(shí),有時(shí)會(huì)遇到由于post所攜帶的數(shù)據(jù)的編碼問題,導(dǎo)致請(qǐng)求失敗,這時(shí)我們就需要改變編碼格式。

r = requests.post(url, headers=headers, data=data)

改成

r = requests.post(url, headers=headers, data=data.encode('utf-8'))
    1. 關(guān)于解決'\u'開頭的字符串轉(zhuǎn)中文的方法

python3的解決辦法:

字符串.encode('utf-8').decode('unicode_escape')

python2:

字符串.decode('unicode_escape')
    1. AttributeError: module 'sys' has no attribute 'setdefaultencoding'

python2:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

用官方工具轉(zhuǎn)換后
python3:

import sys
import imp
imp.reload(sys)
sys.setdefaultencoding("utf-8")

一執(zhí)行就會(huì)報(bào)錯(cuò):

$ python3 1.py
Traceback (most recent call last):
  File "1.py", line 5, in <module>
    sys.setdefaultencoding("utf-8")
AttributeError: module 'sys' has no attribute 'setdefaultencoding'

原因:
Python3字符串默認(rèn)編碼unicode, 所以sys.setdefaultencoding也不存在了

-bash-4.1$ export LC_ALL=C
-bash-4.1$ python3 -c 'import sys; print(sys.stdout.encoding)'
ANSI_X3.4-1968
-bash-4.1$ export LC_ALL=en_US.UTF-8
-bash-4.1$ python3 -c 'import sys; print(sys.stdout.encoding)'
UTF-8
-bash-4.1$ export LC_ALL= 
-bash-4.1$ python3 -c 'import sys; print(sys.stdout.encoding)'
UTF-8
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容