Python3自带工具2to3.py 转换 Python2.x 代码到Python3的操作
作者:CodeMing 时间:2021-11-13 16:52:41
几乎所有的Python 2程序都需要一些修改才能正常地运行在Python 3的环境下。为了简化这个转换过程,Python 3自带了一个叫做2to3的实用脚本(Utility Script),这个脚本会将你的Python 2程序源文件作为输入,然后自动将其转换到Python 3的形式。
本文介绍一下在windows 10 环境下如何使用这个工具:
1)首先要先安装好python3,可到官网下载https://www.python.org/
2)使用Windows 命令提示符(cmd)打开2to3.py 脚本所在位置,如下图:
C:\Users\CodeMing>cd C:\Program Files\Python 3.5\Tools\scripts
3)紧接着运行 2to3.py 脚本
C:\Program Files\Python 3.5\Tools\scripts>python 2to3.py
可以看见在python 2to3.py 后面是需要参数的,我们输入--help 可以看到所需的参数信息。
4)2to3.py 脚本可以单独转换python2.x 代码 到python3,也可以按照目录批量的转换。下面分别举例说明一下:
A 按目录转换
假设我要转换的代码所在目录在:E:\ipv6-master
那么在CMD里面输入:
C:\Program Files\Python 3.5\Tools\scripts>python 2to3.py -w E:\ipv6--master\
B 按指定代码转换
C:\Program Files\Python 3.5\Tools\scripts>python 2to3.py -w E:\ipv6--master\IPV6.py
已知问题:
1)当要转换的代码在C盘的路径下,转换会出问题。显示:拒绝访问。可能是权限问题。
补充:python中2to3工具的使用
python3与python2的还是有诸多的不同,比如说在2中:
print "Hello,World!"
raw_input()
在3里面就成了:
print ("Hello,World!")
input()
所以如果用的python2开发的项目要迁移到3中,就需要进行代码的转换。Python3中自带了个转换工具,下面用个最简单的例子来说说2to3转换工具。
例子:(2to3Test.py 里面只有print这行代码)
# python 2.7.6
# 2to3Test.py
print "Hello,World!"
用python27显然是可以编译的:
D:\Python>python27 2to3Test.py
Hello,World!
用python33就编译不过了,因为3里print是函数,这样写就会有语法错误。
D:\Python>python33 2to3Test.py
File "2to3Test.py", line 1
print "Hello,World!"
^
SyntaxError: invalid syntax
下面用python3中自带的2to3工具进行转换:
D:\Python>python C:\Python33\Tools\Scripts\2to3.py -w 2to3Test.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored 2to3Test.py
--- 2to3Test.py (original)
+++ 2to3Test.py (refactored)
@@ -1 +1 @@
-print "Hello,World!"
+print("Hello,World!")
RefactoringTool: Files that were modified:
RefactoringTool: 2to3Test.py
最后用python33来进行编译,结果显示正确的。
D:\Python>python33 2to3Test.py
Hello,World!
来源:https://blog.csdn.net/u012211419/article/details/51136232
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python OpenCV实现传统图片格式与base64转换
很有意思的SQL多行数据拼接
Python 中的 else详解
提供效率的几个ASP编程技巧
Python使用lambda抛出异常实现方法解析
以Python的Pyspider为例剖析搜索引擎的网络爬虫实现方法
python 解决print数组/矩阵无法完整输出的问题
![](https://img.aspxhome.com/file/2023/3/110553_0s.jpg)
什么是响应式Web设计?怎样进行?
php读取mysql的简单实例
基于Python实现骰子小游戏
![](https://img.aspxhome.com/file/2023/3/128443_0s.jpg)
初窥交互设计
![](https://img.aspxhome.com/file/UploadPic/200910/10/1-90s.jpg)
Python3 文章标题关键字提取的例子
![](https://img.aspxhome.com/file/2023/4/109644_0s.jpg)
Python中的基本数据类型讲解
tensorflow训练中出现nan问题的解决
详解Python中常用的激活函数(Sigmoid、Tanh、ReLU等)
![](https://img.aspxhome.com/file/2023/5/90445_0s.png)
Python正则表达式中的'r'用法总结
![](https://img.aspxhome.com/file/2023/2/109852_0s.png)