如何自动将Python 2.x代码转换成Python3.x代码

Python 3 和 Python 2 不兼容,导致大多数 Python 2.x 程序都无法在 Python 3.x 环境中运行。针对这一问题,Python 官方提供了一个将 Python 2.x 代码自动转换为 Python 3.x 代码的小工具,起名为 2to3,可以将绝大部分的 Python 2.x 代码自动转换成 Python 3.x 代码。

在 Windows 环境中,2to3 工具位于 Python 的安装包内,是一个后缀名为 .py 的源程序文件;在 Linux 环境中,2to3 工具通常需要单独安装。

下面是一段 Python 2.x 版本的代码,无法直接在 Python 3.x 环境中运行。

def my_strcmp(str1,str2):

if str1 <> str2:

print “str1 ≠ str2”

else:

print “str1 == str2”

str1 = “分享网”

str2 = “http://x/python/”

my_strcmp(str1,str2)

就以这段代码为例,教大家借助 2to3 工具在 Windows 和 Linux 环境中将 Python2.x 代码转换为 Python3.x 代码。

Windows环境下的转换

  1. 首先,要安装好 Python 环境,
  2. 在 Python 安装路径下的“Tools\scripts”文件夹里,可以找到 2to3.py 文件。例如,我当前电脑上安装的是 Python 3.6.x 版本,安装到了“G:\Python\Python36”文件夹中,2to3.py 文件保存在 “G:\Python\Python36\Tools\scripts ”文件夹中,如图 1 所示:

image

图 1 Python 2.x 转 Python 3.x 的工具

  1. 将 2to3.py 文件复制到 Python 2.x 程序所在的文件夹里。
  2. win+R组合键打开“运行”窗口,输入cmd后回车打开命令行窗口,将当前位置跳转到 Python 2.x 程序所在的文件夹。例如,程序保存在“E:\change\demo.py”文件中,命令行窗口中依次输入以下指令:

    C:\users\Demo>E:
    E:\>cd change
    E:\change>

  3. 执行如下指令,就可以将 demo.py 文件中的 Python 2.x 代码转换为符合 Python 3.x 语法要求的代码。

    Python 2to3.py -w demo.py

    执行完后,“E:\change” 文件夹中会生成一个 demo.py 文件的备份文件,名称为 demo.py.bak,里边存储的是 Python 2.x 版本的程序。同时,原 demo.py 文件的代码就转换成了符合 Python 3.x 语法要求的代码:

def my_strcmp(str1,str2):

if str1 != str2:

print(“str1 != str2”)

else:

print(“str1 == str2”)

str1 = “分享网”

str2 = “http://x.cn/python/”

my_strcmp(str1,str2)

注意,在使用 2to3.py 转换 python 2.x 代码前,尽量不要把要转换的代码保存在 C 盘中,因此如果保存在 C 盘,可能会因权限问题导致转换不能正常完成。

Linux环境下的转换

Linux 环境中,2to3 工具通常不位于 Python 安装包里,需要单独安装。

以 Ubuntu 系统为例,打开命令行窗口(Terminal),输入2to3 -h命令:

$ 2to3 -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
  ......

出现以上信息,证明当前环境已经安装了 2to3 工具,否则就需要手动安装。

安装 2to3 的方法很简单,执行sudo apt install 2to3命令:

$ sudo apt install 2to3
Reading package lists... Done
Building dependency tree      
Reading state information... Done
......

执行完成后,2to3 工具就安装成功了,大家可以再次执行2to3 -h命令进行验证。

假设 Python 2.x 代码存储在 /home/cyuyan/demo.py 文件中,依次执行如下命令:

$ cd /home/cyuyan/
$ 2to3 -w demo.py

执行完成后,在 /home/cyuyan/ 目录下也会生成一个名为 demo.py.bak 的备份文件,demo.py 文件中就变成了符合 Python 3.x 语法要求的程序。

如何自动将Python 2.x代码转换成Python3.x代码

相关文章:

你感兴趣的文章:

标签云: