如何把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="#">sales@cinesysinc.com</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,即可。

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

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

  1. python2.x脚本转换为python3.x脚本的方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/dushu990/article/details/73549174 python2.x脚本转换为pyt ...

  2. python 内置2to3工具将python2代码转换为python3代码

    python2与python3代码不兼容,如果需要python2代码在python3环境下运行,需要将代码进行转换,本文介绍使用python3内置工具2to3.py对代码进行转换 一:2to3.py在 ...

  3. ios oc 代码 转换为 c++ 描述代码编译过程

    clang -rewrite-objc main.m #import <Foundation/Foundation.h> #import <objc/runtime.h> // ...

  4. 将python2代码转为python3

    将python2代码转为python3 1.2to3在anaconda的/bin文件夹下: 2.打印帮助信息 2to3 --help 3.使用2to3 -W [要转换的python2文件目录] 4.转 ...

  5. 使用Python3自带工具2to3.py 转换 Python2.x 代码 到Python3

    几乎所有的Python 2程序都需要一些修改才能正常地运行在Python 3的环境下.为了简化这个转换过程,Python 3自带了一个叫做2to3的实用脚本(Utility Script),这个脚本会 ...

  6. 再见,Python2。你好,Python3

     文章首发自我的公众号,转载请注明出处~ ​ Python2的退场,意味着一个时代的结束 ​ 我们这一代程序员基本都接触过python2,很多人也是从python2时代一路走来的.但是,是时候说再见了 ...

  7. Python中生成器和迭代器的区别(代码在Python3.5下测试):

    https://blog.csdn.net/u014745194/article/details/70176117 Python中生成器和迭代器的区别(代码在Python3.5下测试):Num01–& ...

  8. 学python2.7简单还是python3.0简单,两者区别

    学python2.7简单还是python3.0简单,谈谈两者区别 1. 使用__future__模块 Python 3.X 引入了一些与Python 2 不兼容的关键字和特性.在Python 2中,可 ...

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

    怎样使用 async & await 一步步将同步代码转换为异步编程 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6079707.html  ...

随机推荐

  1. 设置PlaceHolder的颜色

    input::-webkit-input-placeholder{ color:green; } input::-webkit-input-placeholder { color: #999; } i ...

  2. 压缩、解压缩流GZipStream

    如果要在压缩过程中检查错误或要与其他操作系统所用程序共享压缩数据,则要是用GZipStream类.GZipStream类包含是用GZip数据格式进行压缩和解压缩文件的方法,该类不能用于解压缩大于4GB ...

  3. python选择排序实现与C选择排序实现

    python代码: #coding=utf-8 if __name__=="__main__": arr=[3,2,1,7,11,4,5,8] print "Before ...

  4. ntp服务器池列表

    CentOS: 0.centos.pool.ntp.org 1.centos.pool.ntp.org 2.centos.pool.ntp.org 国内可用的 ntp.fudan.edu.cn 复旦 ...

  5. ios sourecTree

    1, http://www.jianshu.com/p/be9f0484af9d 2, http://blog.csdn.net/viewcode/article/details/42291973  

  6. nginx配置 的话注意几点 1.错误时注意看log 2.天威证书的话,有文档按照其文档一步步配置即可;3每句话的结尾注意千万别丢掉分号

    nginx配置 的话注意几点 1.错误时注意看log  2.天威证书的话,有文档按照其文档一步步配置即可:3每句话的结尾注意千万别丢掉分号:4.配置https时 其转发可以转发到http上 pass_ ...

  7. RehHat enterprise 5.4 安装git

    今天想来研究一下git,就自己安装一个试试,没想到遇到各种问题.经过各种百度和google,终于都解决了,现在来总结一下: 1.安装完redhat 5.4,安装gcc编译器的问题:这个gcc编译器需要 ...

  8. 在Android中建立Android project没有R.java文件

    最近在搞一下安卓,在新建Android工程,既然发现在gen目录下没有R.java这个文件.我当时感到很郁闷,上次建Android工程才好好的,怎么这次既然报错没有R.java.后来我用以下才解决了. ...

  9. Unity 3D 调用摄像头捕获照片 录像

    1,要想调用摄像头首先要打开摄像头驱动,如果用户允许则可以使用. 2,定义WebCamTexture的变量用于捕获单张照片. 3,连续捕获须启用线程. 实现代码: using UnityEngine; ...

  10. .net web api 一

    web api可以提供方便简单可靠的web服务,可以大量的用于不需要提供复杂的soap协议的环境,以简单明了的形式返回数据,在不太复杂的环境中web api可以做为wcf等重级web服务的一种可替代方 ...