龙空技术网

Python2的代码如何转换成Python3?

迷途小书童的Note 76

前言:

此时我们对“python2和3安装后怎样切换”大概比较关心,姐妹们都想要知道一些“python2和3安装后怎样切换”的相关内容。那么小编同时在网上网罗了一些有关“python2和3安装后怎样切换””的相关文章,希望姐妹们能喜欢,大家快快来了解一下吧!

简介

Python2Python3 在语法和某些模块的使用上是有一些差别的,对于一些用 python2 编写的历史项目,要重新启用它们,2to3 是一个不错的转换工具,也是官方提供的工具,不需要安装,可靠性也比较高,它读取 Python 2.x 源代码并应用一系列修复程序将其转换为有效的 Python 3.x 代码。

实操

可以在终端中查看命令支持的所有参数

(base) PS C:\Users\xgx> 2to3.exe -hUsage: 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  -e, --exec-function   Modify the grammar so that exec() 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  -o OUTPUT_DIR, --output-dir=OUTPUT_DIR                        Put output files in this directory instead of                        overwriting the input files.  Requires -n.  -W, --write-unchanged-files                        Also write files even if no changes were required                        (useful with --output-dir); implies -w.  --add-suffix=ADD_SUFFIX                        Append this string to all output filenames. Requires                        -n if non-empty.  ex: --add-suffix='3' will generate                        .py3 files.

下面看一个具体的示例,这是 python2 编写的代码,保存成文件 test.py

def greet(name):    print "Hello, {0}!".format(name)print "What's your name?"name = raw_input()greet(name)

执行转换命令

2to3.exe -w test.py

可以看到,转换过程中会输出2个版本的差异,然后将转换后的内容写入原文件中(即覆盖),而原文件内容会存放在 test.py.bak 中进行备份

(base) PS C:\Users\xgx\Desktop> 2to3.exe -w test.pyRefactoringTool: Skipping optional fixer: bufferRefactoringTool: Skipping optional fixer: idiomsRefactoringTool: Skipping optional fixer: set_literalRefactoringTool: Skipping optional fixer: ws_commaRefactoringTool: Refactored test.py--- test.py     (original)+++ test.py     (refactored)@@ -1,5 +1,5 @@ def greet(name):-    print "Hello, {0}!".format(name)-print "What's your name?"-name = raw_input()+    print("Hello, {0}!".format(name))+print("What's your name?")+name = input() greet(name)RefactoringTool: Files that were modified:RefactoringTool: test.py

如果是文件夹批量转换,命令直接跟上源码文件夹即可,如

2to3.exe -w D:\project

指定输出文件夹,使用 -o 参数;不想要 python2 的备份,使用 -n 参数

参考资料

标签: #python2和3安装后怎样切换 #python2转换为python3