欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python2转换成Python3

Python基础 迷途小书童 8个月前 (07-17) 367次浏览 0个评论

环境

  • windows 11 64bit
  • 2to3

简介

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

实操

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

(base) PS C:\Users\xgx> 2to3.exe -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
  -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.py
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: 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 参数

参考资料

喜欢 (0)

您必须 登录 才能发表评论!