您的位置:首页 > 编程语言 > Python开发

Python3.x和Python2.x版本兼容问题

2018-02-28 09:33 1711 查看

Python3.x和Python2.x版本兼容问题

重组和重命名

标准库

为了一致性和使用起来更容易,Python的标准库在Python 3已经被重组了。所有的模块名现在符合Python代码的风格引导,PEP 8[1];并且一些模块被合并了。2to3包含的固定器可以处理所有的这些,所以这个章节更多的是引起你是否需要不用2to3转换同时支持Python 2和Python 3的兴趣。six模块[2]对大多数重组的标准库的整合都有支持。你可以从six.moves导入重组的模块:
>>> from six.moves import cStringIO
在Python 2这等效于:
>>> from cStringIO import StringIO
然而在Python 3这将等效于:
>>> from io import StringIO
如果你想要不用转换并且不想用six模块同时Python 2和Python 3,这也是很容易的。你只需要偿试从一个位置导入,捕捉错误然后从其他位置导入。它和你放Python 3的位置在前或者在后没有关系,都可以同样很好地起作用:
>>> try:
...     from io import StringIO
... except ImportError:
...     from cStringIO import StringIO
这个表格包含除了另外列出表格的urllib、urllib2 和urlparse重组外的所有标准库的重命名和重组:
Python 2 名字Python 3 名字six名字
anydbmdbm 
BaseHTTPServerhttp.serverBaseHTTPServer
__builtin__builtinsbuiltins
CGIHTTPServerhttp.serverCGIHTTPServer
ConfigParserconfigparserconfigparser
copy_regcopyregcopyreg
cPicklepicklecPickle
cProfileprofile 
cStringIO.StringIOio.StringIOcStringIO
Cookiehttp.cookieshttp_cookies
cookielibhttp.cookiejarhttp_cookiejar
dbhashdbm.bsd 
dbmdbm.ndbm 
dumbdbdbm.dumb 
Dialogtkinter.dialogtkinter_dialog
DocXMLRPCServerxmlrpc.server 
FileDialogtkinter.FileDialogtkinter_filedialog
FixTktkinter._fix 
gdbmdbm.gnu 
htmlentitydefshtml.entitieshtml_entities
HTMLParserhtml.parserhtml_parser
httplibhttp.clienthttp_client
markupbase_markupbase 
Queuequeuequeue
reprreprlibreprlib
robotparserurllib.robotparserurllib_robotparser
ScrolledTexttkinter.scolledtexttkinter_scrolledtext
SimpleDialogtkinter.simpledialogtkinter_simpledialog
SimpleHTTPServerhttp.serverSimpleHTTPServer
SimpleXMLRPCServerxmlrpc.server 
StringIO.StringIOio.StringIO 
SocketServersocketserversocketserver
test.test_supporttest.supporttkinter
Tkintertkintertkinter
Tixtkinter.tixtkinter_tix
Tkconstantstkinter.constantstkinter_constants
tkColorChoosertkinter.colorchoosertkinter_colorchooser
tkCommonDialogtkinter.commondialogtkinter_commondialog
Tkdndtkinter.dndtkinter_dnd
tkFileDialogtkinter.filedialogtkinter_tkfiledialog
tkFonttkinter.fonttkinter_font
tkMessageBoxtkinter.messageboxtkinter_messagebox
tkSimpleDialogtkinter.simpledialogtkinter_tksimpledialog
turtletkinter.turtle 
UserListcollections 
UserStringcollections 
whichdbdbm 
_winregwinregwinreg
xmlrpclibxmlrpc.client 

urllib、urllib2和urlparse

urllib、urllib2和urlparse这三个模块被重组进了urllib.request、urllib.parse和urllib.error这三个新的模块。因为没有six的支持,所有你必须要使用前面提到的try/except技巧。
Python 2 名字移动到
urllib._urlopenerurllib.request
urllib.ContentTooShortErrorurllib.error
urllib.FancyURLOpenerurllib.request
urllib.pathname2urlurllib.request
urllib.quoteurllib.parse
urllib.quote_plusurllib.parse
urllib.splitattrurllib.parse
urllib.splithosturllib.parse
urllib.splitnporturllib.parse
urllib.splitpasswdurllib.parse
urllib.splitporturllib.parse
urllib.splitqueryurllib.parse
urllib.splittagurllib.parse
urllib.splittypeurllib.parse
urllib.splituserurllib.parse
urllib.splitvalueurllib.parse
urllib.unquoteurllib.parse
urllib.unquote_plusurllib.parse
urllib.urlcleanupurllib.request
urllib.urlencodeurllib.parse
urllib.urlopenurllib.request
urllib.URLOpenerurllib.request
urllib.urlretrieveurllib.request
urllib2.AbstractBasicAuthHandlerurllib.request
urllib2.AbstractDigestAuthHandlerurllib.request
urllib2.BaseHandlerurllib.request
urllib2.build_openerurllib.request
urllib2.CacheFTPHandlerurllib.request
urllib2.FileHandlerurllib.request
urllib2.FTPHandlerurllib.request
urllib2.HTTPBasicAuthHandlerurllib.request
urllib2.HTTPCookieProcessorurllib.request
urllib2.HTTPDefaultErrorHandlerurllib.request
urllib2.HTTPDigestAuthHandlerurllib.request
urllib2.HTTPErrorurllib.request
urllib2.HTTPHandlerurllib.request
urllib2.HTTPPasswordMgrurllib.request
urllib2.HTTPPasswordMgrWithDefaultRealmurllib.request
urllib2.HTTPRedirectHandlerurllib.request
urllib2.HTTPSHandlerurllib.request
urllib2.install_openerurllib.request
urllib2.OpenerDirectorurllib.request
urllib2.ProxyBasicAuthHandlerurllib.request
urllib2.ProxyDigestAuthHandlerurllib.request
urllib2.ProxyHandlerurllib.request
urllib2.Requesturllib.request
urllib2.UnknownHandlerurllib.request
urllib2.URLErrorurllib.request
urllib2.urlopenurllib.request
urlparse.parse_qsurllib.parse
urlparse.parse_qslurllib.parse
urlparse.urldefragurllib.parse
urlparse.urljoinurllib.parse
urlparse.urlparseurllib.parse
urlparse.urlspliturllib.parse
urlparse.urlunparseurllib.parse
urlparse.urlunspliturllib.parse

移除的模块

一些标准库模块已经被丢弃。UserDict是一个,但这些类中的一部分有一些差不多的替代品,但不是完全的兼容。更多信息见取代UserDict。大多数其他被丢弃的模块都是些已经被替换掉很长久的模块,或者是一些给支持时期不长的特殊平台的模块。这个规则适用并例外的是异常模块。它包含异常的等级,但所有它们也是内置的,所以你从来都不需要从异常模块导入任何东西。因此它已经在Python 3被完全移除了。除了给Solaris、RIX和Mac OS 9的特殊模块,在Python 3中被移除模块列表:
模块名注释
audiodev 
Bastion 
bsddb185被bsddb3替代
bsddb3在CheeseShop可用
Canvas 
cfmfile 
cl 
commands 
compiler 
dircache 
dl被ctypes替代
exception见前面
fpformat 
htmllib被html.parser替代
ihooks 
imageop 
imputil 
linuxaudiodev被ossaudiodev替代
md5被hashlib替代
mhlib 
mimetools被email替代
MimeWriter被email替代
mimify被email替代
multifile被email替代
mutex 
new 
popen2被subprocess替代
posixfile 
pure 
rexec 
rfc822被email替代
sha被hashlib替代
sgmllib 
sre被re替代
stat被os.stat()替代
stringold 
sunaudio 
sv 
test.testall 
thread被threading替代
timing 
toaiff 
user 

被移动的内置函数

有几个内置函数被移到了标准库。你可以用相似的方式来处理他们,通过偿试从Python 3的位置导入他们并在失败时不做任何事:
>>> try:
...     from imp import reload
... except ImportError:
...     pass
被移动的内置函数是:
Python 2 名Python 3 名six 名
intern()sys.intern() 
reduce()functools.reduce()reduce
reload()imp.reload()reload_module

string模块调动

有几个函数存在于string模块,同时也作为str类型及实体的方法存在。这些现在已经被从string模块移除。你还可以在字符串实体或者从str类型中使用他们。所以在Python 2可以写成:
>>> import string
>>> string.upper('Dinsdale!')
'DINSDALE!'
现在需要被写成下面两种方式中的一个:
>>> 'Dinsdale!'.upper()
'DINSDALE!'
>>> str.upper('Dinsdale!')
'DINSDALE!'
第一种方式是做这个最常见的一个,但是换成第二个方式可以做简单的查找和替换。被移除的函数是capitalize()、 center()、 count()、expandtabs()、 find()、index()、 join()、ljust()、lower()、lstrip()、maketrans()、 replace()、 rfind()、rindex()、 rjust()、rsplit()、rstrip()、split()、strip()、swapcase()、translate()、upper()及 zfill()。此外atof()、atoi()和atol()函数被移除,并且被把字符串值变成浮点和整数的构造器取代。因为这些函数从Python 2.0起就废弃了,也极不像你会实际使用它们的样子。

函数及方法属性的重命名

在函数和方法中的很多特殊属性是在决定Python应该用“双下划线”方法来描述被Python使用名前就被命名了。如果你不使用2ot3处理这个的最简单方法是要根据Python版本用属性史定义一个变量并使用getattr来访问属性。然而,这个不能在im_class重命名的情况下的起作用,所以你需要一个函数来取得结果:
>>> import sys
>>> if sys.version_info < (3,):
...     defaults_attr = 'func_defaults'
...     get_method_class = lambda x: x.im_class
... else:
...     defaults_attr = '__defaults__'
...     get_method_class = lambda x: x.__self__.__class__
>>> class Test(object):
...     def hasdefaults(a=1, b=2):
...         pass
>>> method = Test().hasdefaults
>>> getattr(method, defaults_attr)
(1, 2)
>>> get_method_class(method)
<class 'Test'>
Six已经定义了函数来重新得到最常见的属性名: 
Python 2 名Python 3 名six 函数
func_closure__closure__ 
func_doc__doc__ 
func_globals__globals__ 
func_name__name__ 
func_defaults__defaults__get_function_defaults()
func_code__code__get_function_code()
func_dict__dict__ 
im_func__func__get_method_function()
im_self__self__get_method_self()
im_class__self__.__class__ 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: