几乎所有的python 2程序都需要一些修改才能正常地运行在python 3的环境下。为了简化这个转换过程,python 3自带了一个叫做2to3的实用脚本(utility script),这个脚本会将你的python 2程序源文件作为输入,然后自动将其转换到python 3的形式。

本文介绍一下在windows 10 环境下如何使用这个工具:

1)首先要先安装好python3,可到官网下载

2)使用windows 命令提示符(cmd)打开2to3.py 脚本所在位置,如下图:

c:\users\codeming>cd c:\program files\python 3.5\tools\scripts

3)紧接着运行 2to3.py 脚本

c:\program files\python 3.5\tools\scripts>python 2to3.py

可以看见在python 2to3.py 后面是需要参数的,我们输入–help 可以看到所需的参数信息。

4)2to3.py 脚本可以单独转换python2.x 代码 到python3,也可以按照目录批量的转换。下面分别举例说明一下:

a 按目录转换

假设我要转换的代码所在目录在:e:\ipv6-master

那么在cmd里面输入:

c:\program files\python 3.5\tools\scripts>python 2to3.py -w e:\ipv6–master\

b 按指定代码转换

c:\program files\python 3.5\tools\scripts>python 2to3.py -w e:\ipv6–master\ipv6.py

已知问题:

1)当要转换的代码在c盘的路径下,转换会出问题。显示:拒绝访问。可能是权限问题。

补充:python中2to3工具的使用

python3与python2的还是有诸多的不同,比如说在2中:

print "hello,world!"
raw_input()

在3里面就成了:

print ("hello,world!")
input()

所以如果用的python2开发的项目要迁移到3中,就需要进行代码的转换。python3中自带了个转换工具,下面用个最简单的例子来说说2to3转换工具。

例子:(2to3test.py 里面只有print这行代码)

# python 2.7.6
# 2to3test.py
 
print "hello,world!"

用python27显然是可以编译的:

d:\python>python27 2to3test.py
hello,world!

用python33就编译不过了,因为3里print是函数,这样写就会有语法错误。

d:\python>python33 2to3test.py
 file "2to3test.py", line 1
  print "hello,world!"
            ^
syntaxerror: invalid syntax

下面用python3中自带的2to3工具进行转换:

d:\python>python c:\python33\tools\scriptsto3.py -w 2to3test.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 2to3test.py
--- 2to3test.py (original)
+++ 2to3test.py (refactored)
@@ -1 +1 @@
-print "hello,world!"
+print("hello,world!")
refactoringtool: files that were modified:
refactoringtool: 2to3test.py

最后用python33来进行编译,结果显示正确的。

d:\python>python33 2to3test.py
hello,world!

总结

1. 目录. c:\python33\tools\scripts\2to3.py. 其实在python2.6,2.7中都存在这个工具。

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

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

4. 不想要生成bak文件,再加上-n即可。 bak最好还是有。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。