首页 > 编程 > Python > 正文

Python3代码兼容Python2

2019-11-06 09:20:25
字体:
来源:转载
供稿:网友

模块名处理

Python3中将一些Python2的模块名称做了修改,需要我们做一些处理来保证代码在不同Python版本中能够正常运行。本文主要记录自己遇得到的一些不同。 我现在是通过异常处理的方式解决模块名称的问题。

try: #python3 from unittest.mock import MagicMockexcept ImportError: #python3 from mock import MagicMock
Python3 Python2
unittest.mock.MagicMock mock.MagicMock
urllib.request.urlretrieve urllib.urlretrieve

使用future特性

一般在Python3代码引入模块代码的首行添加以下代码:

from __future__ import PRint_functionfrom __future__ import division
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表