python - 3to2 | 2to3 - python3转python2 | python2转python3
文章目录
注意:文件名不要带中文。
3转2
3to2
安装
# 安装3to2
$ pip3 install 3to2
使用
# 显示帮助
$ 3to2 -h
Usage: 3to2 [options] file|dir ...
# 转换单个文件
$ 3to2 -w <filepath>
-w, --write Write back modified files
-n, --nobackups Donot write backups for modified files.
# 转换整个文件夹下所有文件
$ 3to2 -w <dirpath>
py-backwards
https://github.com/nvbn/py-backwards
安装
$ pip install py-backwards
使用
$ py-backwards -i src -o compiled -t 2.7
$ py-backwards -i input.py -o output.py -t 2.7
2转3
2to3
自动将 Python 2 代码转为 Python 3 代码
2to3适用 修复器 来转换代码,其支持库lib2to3,
注释和缩进都会在转换过程中保持不变。
使用
转换前
def greet(name):
print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)
转换命令
# 预览转换
$ 2to3 example.py
# 覆盖原文件
$ 2to3 -w example.py
$ 2to3 -nw example.py # 不创建源文件副本
转换后
def greet(name):
print("Hello, {0}!".format(name))
print("What's your name?")
name = input()
greet(name)
参考文档
}!".format(name))
print(“What’s your name?”)
name = input()
greet(name)
# 参考文档
[nvbn](https://github.com/nvbn) / **py-backwards** https://github.com/nvbn/py-backwards