为了一致性和使用起来更容易,Python的标准库在Python 3已经被重组了。全部的模块名如今符合Python代码的风格引导,PEP 8[1];而且一些模块被合并了。html
2to3包含的固定器能够处理全部的这些,因此这个章节更多的是引发你是否须要不用2to3转换同时支持Python 2和Python 3的兴趣。python
six模块[2]对大多数重组的标准库的整合都有支持。你能够从six.moves导入重组的模块:linux
>>> from six.moves import cStringIO
在Python 2这等效于:api
>>> from cStringIO import StringIO
然而在Python 3这将等效于:cookie
>>> from io import StringIO
若是你想要不用转换而且不想用six模块同时Python 2和Python 3,这也是很容易的。你只须要偿试从一个位置导入,捕捉错误而后从其余位置导入。它和你放Python 3的位置在前或者在后没有关系,均可以一样很好地起做用:socket
>>> try: ... from io import StringIO ... except ImportError: ... from cStringIO import StringIO
这个表格包含除了另外列出表格的urllib、urllib2 和urlparse重组外的全部标准库的重命名和重组:函数
Python 2 名字 | Python 3 名字 | six名字 |
---|---|---|
anydbm | dbm | |
BaseHTTPServer | http.server | BaseHTTPServer |
__builtin__ | builtins | builtins |
CGIHTTPServer | http.server | CGIHTTPServer |
ConfigParser | configparser | configparser |
copy_reg | copyreg | copyreg |
cPickle | pickle | cPickle |
cProfile | profile | |
cStringIO.StringIO | io.StringIO | cStringIO |
Cookie | http.cookies | http_cookies |
cookielib | http.cookiejar | http_cookiejar |
dbhash | dbm.bsd | |
dbm | dbm.ndbm | |
dumbdb | dbm.dumb | |
Dialog | tkinter.dialog | tkinter_dialog |
DocXMLRPCServer | xmlrpc.server | |
FileDialog | tkinter.FileDialog | tkinter_filedialog |
FixTk | tkinter._fix | |
gdbm | dbm.gnu | |
htmlentitydefs | html.entities | html_entities |
HTMLParser | html.parser | html_parser |
httplib | http.client | http_client |
markupbase | _markupbase | |
Queue | queue | queue |
repr | reprlib | reprlib |
robotparser | urllib.robotparser | urllib_robotparser |
ScrolledText | tkinter.scolledtext | tkinter_scrolledtext |
SimpleDialog | tkinter.simpledialog | tkinter_simpledialog |
SimpleHTTPServer | http.server | SimpleHTTPServer |
SimpleXMLRPCServer | xmlrpc.server | |
StringIO.StringIO | io.StringIO | |
SocketServer | socketserver | socketserver |
test.test_support | test.support | tkinter |
Tkinter | tkinter | tkinter |
Tix | tkinter.tix | tkinter_tix |
Tkconstants | tkinter.constants | tkinter_constants |
tkColorChooser | tkinter.colorchooser | tkinter_colorchooser |
tkCommonDialog | tkinter.commondialog | tkinter_commondialog |
Tkdnd | tkinter.dnd | tkinter_dnd |
tkFileDialog | tkinter.filedialog | tkinter_tkfiledialog |
tkFont | tkinter.font | tkinter_font |
tkMessageBox | tkinter.messagebox | tkinter_messagebox |
tkSimpleDialog | tkinter.simpledialog | tkinter_tksimpledialog |
turtle | tkinter.turtle | |
UserList | collections | |
UserString | collections | |
whichdb | dbm | |
_winreg | winreg | winreg |
xmlrpclib | xmlrpc.client |
urllib、urllib2和urlparse这三个模块被重组进了urllib.request、urllib.parse和urllib.error这三个新的模块。由于没有six的支持,全部你必需要使用前面提到的try/except技巧。ui
Python 2 名字 | 移动到 |
---|---|
urllib._urlopener | urllib.request |
urllib.ContentTooShortError | urllib.error |
urllib.FancyURLOpener | urllib.request |
urllib.pathname2url | urllib.request |
urllib.quote | urllib.parse |
urllib.quote_plus | urllib.parse |
urllib.splitattr | urllib.parse |
urllib.splithost | urllib.parse |
urllib.splitnport | urllib.parse |
urllib.splitpasswd | urllib.parse |
urllib.splitport | urllib.parse |
urllib.splitquery | urllib.parse |
urllib.splittag | urllib.parse |
urllib.splittype | urllib.parse |
urllib.splituser | urllib.parse |
urllib.splitvalue | urllib.parse |
urllib.unquote | urllib.parse |
urllib.unquote_plus | urllib.parse |
urllib.urlcleanup | urllib.request |
urllib.urlencode | urllib.parse |
urllib.urlopen | urllib.request |
urllib.URLOpener | urllib.request |
urllib.urlretrieve | urllib.request |
urllib2.AbstractBasicAuthHandler | urllib.request |
urllib2.AbstractDigestAuthHandler | urllib.request |
urllib2.BaseHandler | urllib.request |
urllib2.build_opener | urllib.request |
urllib2.CacheFTPHandler | urllib.request |
urllib2.FileHandler | urllib.request |
urllib2.FTPHandler | urllib.request |
urllib2.HTTPBasicAuthHandler | urllib.request |
urllib2.HTTPCookieProcessor | urllib.request |
urllib2.HTTPDefaultErrorHandler | urllib.request |
urllib2.HTTPDigestAuthHandler | urllib.request |
urllib2.HTTPError | urllib.request |
urllib2.HTTPHandler | urllib.request |
urllib2.HTTPPasswordMgr | urllib.request |
urllib2.HTTPPasswordMgrWithDefaultRealm | urllib.request |
urllib2.HTTPRedirectHandler | urllib.request |
urllib2.HTTPSHandler | urllib.request |
urllib2.install_opener | urllib.request |
urllib2.OpenerDirector | urllib.request |
urllib2.ProxyBasicAuthHandler | urllib.request |
urllib2.ProxyDigestAuthHandler | urllib.request |
urllib2.ProxyHandler | urllib.request |
urllib2.Request | urllib.request |
urllib2.UnknownHandler | urllib.request |
urllib2.URLError | urllib.request |
urllib2.urlopen | urllib.request |
urlparse.parse_qs | urllib.parse |
urlparse.parse_qsl | urllib.parse |
urlparse.urldefrag | urllib.parse |
urlparse.urljoin | urllib.parse |
urlparse.urlparse | urllib.parse |
urlparse.urlsplit | urllib.parse |
urlparse.urlunparse | urllib.parse |
urlparse.urlunsplit | urllib.parse |
一些标准库模块已经被丢弃。UserDict是一个,但这些类中的一部分有一些差很少的替代品,但不是彻底的兼容。更多信息见取代UserDict。url
大多数其余被丢弃的模块都是些已经被替换掉很长久的模块,或者是一些给支持时期不长的特殊平台的模块。这个规则适用并例外的是异常模块。它包含异常的等级,但全部它们也是内置的,因此你历来都不须要从异常模块导入任何东西。所以它已经在Python 3被彻底移除了。spa
除了给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模块,同时也做为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__ |
附注:
[1] | http://www.python.org/dev/peps/pep-0008/ |
[2] | http://pypi.python.org/pypi/six |
本文地址:http://my.oschina.net/soarwilldo/blog/538255
在湖闻樟注:
原文http://python3porting.com/stdlib.html