0
Python2转换成Python3
source link: https://xugaoxiang.com/2023/07/17/python2-to-python3/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Python2转换成Python3 - 迷途小书童的Note迷途小书童的Note
- windows 11 64bit
Python2
和 Python3
在语法和某些模块的使用上是有一些差别的,对于一些用 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
参数
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK