如何把Python2的代码转换为Python3的代码

如何把Python2的代码转换为Python3的代码

注:

如果对于python2和python3不熟悉的,可以参考:

【整理】总结Python2(Python 2.x版本)和Python3(Python 3.x版本)之间的区别


之前有机会接触到,将Python2的代码转换为Python3的代码。

经过一番折腾,大概有了基本概念了。

现在简要整理一下,关于如何将Python 2.x的代码,转换为Python 3.x的代码。



把Python 2.x的代码转换为Python 3.x代码的方法

1.自己手动转换

这个不必多说,如果只是涉及很少的函数,比如print等。

那么自己改改代码,也就可以了。

2.利用Python内置(Python脚本)工具,帮你自动转换

Python 2.x版本,比如我安装的Python 2.7.2,其在windows下载安装好之后,就自带了相关的一些有用的工具。

其中一个叫做2to3.py,就是用来帮你实现,将Python 2.x的代码,转换为Python 3.x的代码的。

其位置位于:Python安装的根目录\Python27\Tools\Scripts\2to3.py

【如何利用2to3.py,实现将Python 2.x的代码,转换为Python 3.x的代码】 
比如我手上有个Python 2.x的python脚本:

D:\tmp\tmp_dev_root\python\python2_to_python3\34563264_data_from_site.py

现在,想要将其转换为Python 3.x的代码。

可以通过打开windows的cmd,定位至该要转换的脚本下,然后运行

D:\tmp\WordPress\DevRoot\Python27\Tools\Scripts\2to3.py -w 34563264_data_from_site.py

即可成功转换,对应的执行结果为:

?


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

D:\tmp\tmp_dev_root\python\python2_to_python3>D:\tmp\WordPress\DevRoot\Python27\Tools\Scripts\2to3.py -w 34563264_data_from_site.py

RefactoringTool: Skipping implicit fixer: buffer

RefactoringTool: Skipping implicit fixer: idioms

RefactoringTool: Skipping implicit fixer: set_literal

RefactoringTool: Skipping implicit fixer: ws_comma

RefactoringTool: Refactored 34563264_data_from_site.py

--- 34563264_data_from_site.py  (original)

+++ 34563264_data_from_site.py  (refactored)

@@ -18,7 +18,7 @@

 import time;

 import codecs;

 import logging;

-import urllib;

+import urllib.request, urllib.parse, urllib.error;

 from datetime import datetime,timedelta;

 from optparse import OptionParser;

 from string import Template,replace;

@@ -90,7 +90,7 @@

         foundPhone = eachItemSoup.find(attrs={"class":"phone"});

         logging.debug("foundPhone=%s", foundPhone);

         if(foundPhone):

-            foundPhoneUni = unicode(foundPhone);

+            foundPhoneUni = str(foundPhone);

             logging.debug("foundPhoneUni=%s", foundPhoneUni);

             # case 1:

             #<p class="phone"><strong>phone:</strong>&nbsp;800.206.7886<br />

@@ -122,7 +122,7 @@

         foundWeb = eachItemSoup.find(attrs={"class":"web"});

         logging.debug("foundWeb=%s", foundWeb);

         if(foundWeb):

-            foundWebUni = unicode(foundWeb);

+            foundWebUni = str(foundWeb);

             logging.debug("foundWebUni=%s", foundWebUni);

             # <p class="web"><strong>e-mail:</strong>&nbsp;<a href="#">[email protected]</a><br />

@@ -151,7 +151,7 @@

         foundAddr = eachItemSoup.find(attrs={"class":"addr"});

         logging.debug("foundAddr=%s", foundAddr);

         if(foundAddr):

-            foundAddrUni = unicode(foundAddr);

+            foundAddrUni = str(foundAddr);

             # <p class="addr">

                 # <strong>address:</strong>&nbsp;740 SW 21st Ave, Suite #310<br />

RefactoringTool: Files that were modified:

RefactoringTool: 34563264_data_from_site.py

此时,你可以看到原先的34563264_data_from_site.py,已经变成了Python 3.x的代码了。

对应的,也多出一个bak文件:34563264_data_from_site.py.bak,两者比较一下,即可看出区别:

当前,对于2to3.py本身,也可以通过help查看到更多的用法:

?


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

D:\tmp\tmp_dev_root\python\python2_to_python3>D:\tmp\WordPress\DevRoot\Python27\Tools\Scripts\2to3.py -h

Usage: 2to3 [options] file|dir ...

Options:

  -h, --help            show this help message and exit

  -d, --doctests_only   Fix up doctests only

  -f FIX, --fix=FIX     Each FIX specifies a transformation; default: all

  -j PROCESSES, --processes=PROCESSES

                        Run 2to3 concurrently

  -x NOFIX, --nofix=NOFIX

                        Prevent a transformation from being run

  -l, --list-fixes      List available transformations

  -p, --print-function  Modify the grammar so that print() is a function

  -v, --verbose         More verbose logging

  --no-diffs            Don‘t show diffs of the refactoring

  -w, --write           Write back modified files

  -n, --nobackups       Don‘t write backups for modified files

此处只多解释几句:

(1)如果上述不加-w参数,则默认只是把转换过程所对应的diff内容打印输出到当前窗口而已。

(2)加了-w,就是把改动内容,写回到原先的文件了。

(3)不想要生成bak文件,再加上-n即可。

(4)不想看到那一堆输出的内容,加上–no-diffs,即可。

其他的,就不多介绍了。感兴趣的可以自己去继续折腾。

时间: 2024-08-30 09:06:32

如何把Python2的代码转换为Python3的代码的相关文章

使用python3自带工具2to3.py 转换 python2.x 代码 到python3

几乎所有的Python 2程序都需要一些修改才能正常地运行在Python 3的环境下.为了简化这个转换过程,Python 3自带了一个叫做2to3的实用脚本(Utility Script),这个脚本会将你的Python 2程序源文件作为输入,然后自动将其转换到Python 3的形式. 本文介绍一下在windows 10 环境下如何使用这个工具: 1)首先要先安装好python3,可到官网下载https://www.python.org/ 2)使用Windows 命令提示符(cmd)打开2to3.

windows XP上实现python2.7.5和python3.4.3共存

windows XP上实现python2.7.5和python3.4.3共存过程记录: 1. 首先安装python2.7.5和python3.4.3,两个版本安装顺序不分前后; 2. 检查系统环境变量中是否存在以下四个变量,缺少则手动加入 c:\Python27; c:\Python27\Scripts; c:\Python34; c:\Python34\Scripts; (python安装路径为C:Python27则环境变量为c:\Python27;python安装路径为D:Python27则

[.NET] 使用 async &amp; await 一步步将同步代码转换为异步编程

使用 async & await 一步步将同步代码转换为异步编程 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6079707.html  序 上次,博主通过<利用 async & await 的异步编程>一文介绍了 async & await 的基本用法及异步的控制流和一些其它的东西. 今天,博主打算从创建一个普通的 WPF 应用程序开始,看看如何将它逐步转换成一个异步的解决方案.你知道吗?使用 Visual Studi

Birdge.NET:将C#代码转换为JavaScript

Birdge.NET是一个可以将C#代码转换为JavaScript的开源编译器,由Object.NET于2015年5月推出.它允许开发者使用C#编写平台独立的移动.Web和桌面应用,并运行在iOS.Windows.Mac.Linux及其它任意支持JavaScript的设备上. Birdge.NET的最新版本是2015年8月17日发布的1.8版本.该版本的一项特性是支持多平台操作系统.这一特性可以让Birdge.NET本身运行在多个平台上.目前,Birdge.NET可以运行在Windows.Lin

python2.7升级到python3后,用pip进行安装时报Fatal error in launcher:Unbale to create process using`&quot;&quot;

解决:python2.7升级到python3后,用pip进行安装时报Fatal error in launcher:Unbale to create process using`"" 通过查资料查到:http://www.scriptscoop2.com/t/9cebc32c6ebc/python-fatal-error-in-launcher-unable-to-create-process-using-c-program-files.html 借鉴MiguelCldn 提供的方法,

Python人工智能之图片识别,Python3一行代码实现图片文字识别

1.Python人工智能之图片识别,Python3一行代码实现图片文字识别 2.tesseract-ocr安装包和中文语言包 注意: 原文地址:https://www.cnblogs.com/jycjy/p/8799295.html

JS实现统一社会信用代码的效验(组织机构代码效验)

参考原文https://blog.csdn.net/hdhxby/article/details/56015370 部分错误,修改整合了下 想查询数据的,请点击:统一信用代码查询地址 查看效验规则点击: GB 32100-2015 法人和其他组织统一社会信用代码编码规则 代码实现如下,复制后可以直接使用验证. var v =new Tyshyxdm().verify('91331081307655191L');alert(v);//统一社会信用代码function Tyshyxdm() { th

提取代码中的部分代码字段

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-

使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用

使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用 选择调用的进程为 24 i386 getuid sys_getuid1647 i386 getgid sys_getgid16 使用库函数API方式 使用C代码中嵌入汇编代码方式