使用开源django项目时发现项目python版本为2.7. 而python2在2020年后不再支持更新,相应的许多软件的新版本都不支持python2,为了兼容性需要升级python. 本文对比手动和脚本2to3升级python2过程,验证了脚本2to3相当好用,仅需手动修改python使用路径为python3路径及编码方式即可完成升级
1.使用2to3把python2转为python3:
1.1. 获取2to3:从官网https://www.python.org/downloads/
下载相应版本的,2to3在目录
Python-3.x.x/Tools/scripts/
下
1.2. 执行转换:在django项目下运行:python 2to3 -w ./ >diff.py
即把django项目里的python2转为python3, 转换内容存入diff.py便于查查看, diff.py里的内容类似vimdiff的效果
注:2to3转换内容,可以查看具体说明
https://docs.python.org/zh-cn/3.7/library/2to3.html
2.把urls.py里的python2路径改成python3路径,如已是python3路径不需修改
#!/bin/python3
3.编码使用utf-8: 项目原使用gbk编码汉字英文有兼容问题,改成成utf-8后解决的
3.1. 直接把gbk替换成utf-8
3.2. 使用bytes函数,把json字符串转为utf-8类型bytes对象供Request
4.手动python2升级python3主要修改, 标记-2to3 have
为脚本2to3转换提供内容
1 --2to3 have
2 -from models import Envs
3 +from .models import Envs
4
5 --2to3 have
6 -if config.has_key(user):
7 +if user in config:
8
9 urls.py
10 -#!/usr/bin/env python2.7
11 +#!/bin/python3
12
13 --2to3 have
14 -import sys
15 -reload(sys)
16 +import importlib,sys
17 +importlib.reload(sys)
18
19 -with codecs.open(entry_file,encoding='gbk') as fp:
20 +with codecs.open(entry_file, encoding='utf8') as fp:
21
22 --2to3 have
23 -import urllib2
24 +import urllib.request
25
26 --2to3 have
27 -request = urllib2.Request(url=url, headers=headers, data=json.dumps(data))
28 -response = urllib2.urlopen(request)
29
30 +data = bytes(json.dumps(data), "utf8");
31 +request = urllib.request.Request(url=url, headers=headers, data=data)
32 +response = urllib.request.urlopen(request)
33
34 --2to3 have
35 -def unicode(self):
36 +def str(self):
37
38 --2to3 have dict part
39 -for k,v in config.iteritems():
40 +for k,v in config.items():
41
42 --2to3 have
43 -except Exception,ex:
44 +except Exception as ex:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有