'''Python Standard Library''' ''翻译: Python 江湖群'' 2008-03-28 13:11:55 <> ---- [index.html 返回首页] ---- = 1. 执行支持模块 = 就是其他模块中用到的模块. ---- == 1.1. dospath 模块 == {{{dospath}}} 模块(参见 [[#eg-13-1|Example 13-1]] )提供了 DOS 平台下的 {{{os.path}}} 功能. 你可以使用它在其他平台处理 DOS 路径. ==== 1.1.0.1. Example 13-1. 使用 dospath 模块 ==== {{{ File: dospath-example-1.py import dospath file = "/my/little/pony" print "isabs", "=>", dospath.isabs(file) print "dirname", "=>", dospath.dirname(file) print "basename", "=>", dospath.basename(file) print "normpath", "=>", dospath.normpath(file) print "split", "=>", dospath.split(file) print "join", "=>", dospath.join(file, "zorba") *B*isabs => 1 dirname => /my/little basename => pony normpath => \my\little\pony split => ('/my/little', 'pony') join => /my/little/pony\zorba*b* }}} 注意 Python 的 DOS 支持可以使用斜杠和反斜杠作为目录分隔符. ---- == 1.2. macpath 模块 == {{{macpath}}} 模块( 参见 [[#eg-13-2|Example 13-2]] )提供了 Macintosh 平台下的 {{{os.path}}} 功能. 你也可以使用它在其他平台处理 Macintosh 路径. ==== 1.2.0.1. Example 13-2. 使用 macpath 模块 ==== {{{ File: macpath-example-1.py import macpath file = "my:little:pony" print "isabs", "=>", macpath.isabs(file) print "dirname", "=>", macpath.dirname(file) print "basename", "=>", macpath.basename(file) print "normpath", "=>", macpath.normpath(file) print "split", "=>", macpath.split(file) print "join", "=>", macpath.join(file, "zorba") *B*isabs => 1 dirname => my:little basename => pony normpath => my:little:pony split => ('my:little', 'pony') join => my:little:pony:zorba*b* }}} ---- == 1.3. ntpath 模块 == {{{ntpath}}} 模块( 参见 [[#eg-13-3|Example 13-3]] )提供了 Windows 平台下的 {{{os.path}}} 功能. 你也可以使用它在其他平台处理 Windows 路径. ==== 1.3.0.1. Example 13-3. 使用 ntpath 模块 ==== {{{ File: ntpath-example-1.py import ntpath file = "/my/little/pony" print "isabs", "=>", ntpath.isabs(file) print "dirname", "=>", ntpath.dirname(file) print "basename", "=>", ntpath.basename(file) print "normpath", "=>", ntpath.normpath(file) print "split", "=>", ntpath.split(file) print "join", "=>", ntpath.join(file, "zorba") *B*isabs => 1 dirname => /my/little basename => pony normpath => \my\little\pony split => ('/my/little', 'pony') join => /my/little/pony\zorba*b* }}} 注意该模块可以同时使用斜杠和反斜杠作为目录分隔符. ---- == 1.4. posixpath 模块 == {{{posixpath}}} 模块( 参见 [[#eg-13-4|Example 13-4]] )提供了 Unix 和其他 POSIX 兼容平台下的 {{{os.path}}} 功能. 你也可以使用它在其他平台处理 POSIX 路径. 另外, 它也可以处理 URL . ==== 1.4.0.1. Example 13-4. 使用 posixpath 模块 ==== {{{ File: posixpath-example-1.py import posixpath file = "/my/little/pony" print "isabs", "=>", posixpath.isabs(file) print "dirname", "=>", posixpath.dirname(file) print "basename", "=>", posixpath.basename(file) print "normpath", "=>", posixpath.normpath(file) print "split", "=>", posixpath.split(file) print "join", "=>", posixpath.join(file, "zorba") *B*isabs => 1 dirname => /my/little basename => pony normpath => /my/little/pony split => ('/my/little', 'pony') join => /my/little/pony/zorba*b* }}} ---- == 1.5. strop 模块 == (已废弃) {{{strop}}} 为 {{{string}}} 模块中的大多函数提供了底层 C 语言实现. {{{string}}} 模块会自动调用它, 所以一般你不需要直接使用它. 不过在导入 Python 模块之前处理路径的时候你可能会用到它. 如 [[#eg-13-5|Example 13-5]] 所示. ==== 1.5.0.1. Example 13-5. 使用 strop 模块 ==== {{{ File: strop-example-1.py import strop import sys # assuming we have an executable named ".../executable", add a # directory named ".../executable-extra" to the path if strop.lower(sys.executable)[-4:] == ".exe": extra = sys.executable[:-4] # windows else: extra = sys.executable sys.path.insert(0, extra + "-extra") import mymodule }}} 在 Python 2.0 及以后版本中, 你应该使用字符串方法代替 {{{strop}}} , 例如在上边的代码中. 使用 "{{{sys.executable.lower()}}}" 替换 "{{{strop.lower(sys.executable)}}}" . ---- == 1.6. imp 模块 == {{{imp}}} 模块包含的函数可以用于实现自定义的 import 行为. [[#eg-13-6|Example 13-6]] 重载了 {{{import}}} 语句, 实现了对模块来源的记录功能. ==== 1.6.0.1. Example 13-6. 使用 imp 模块 ==== {{{ File: imp-example-1.py import imp import sys def my_import(name, globals=None, locals=None, fromlist=None): try: module = sys.modules[name] # already imported? except KeyError: file, pathname, description = imp.find_module(name) print "import", name, "from", pathname, description module = imp.load_module(name, file, pathname, description) return module import _ _builtin_ _ _ _builtin_ _._ _import_ _ = my_import *B*import xmllib import xmllib from /python/lib/xmllib.py ('.py', 'r', 1) import re from /python/lib/re.py ('.py', 'r', 1) import sre from /python/lib/sre.py ('.py', 'r', 1) import sre_compile from /python/lib/sre_compile.py ('.py', 'r', 1) import _sre from /python/_sre.pyd ('.pyd', 'rb', 3)*b* }}} 注意这里的导入功能不支持包. 具体实现请参阅 {{{knee}}} 模块的源代码. ---- == 1.7. new 模块 == {{{new}}} 模块是一个底层的模块, 你可以使用它来创建不同的内建对象, 例如类对象, 函数对象, 以及其他由 Python 运行时系统创建的类型. [[#eg-13-7|Example 13-7]] 展示了该模块的使用. 如果你使用的是 1.5.2 版本 , 那么你有可能需要重新编译 Python 来使用这个模块, 在默认情况下并不是所有平台都有这个模块. 在 2.0 及以后版本中, 不需要这么做. ==== 1.7.0.1. Example 13-7. 使用 new 模块 ==== {{{ File: new-example-1.py import new class Sample: a = "default" def _ _init_ _(self): self.a = "initialised" def _ _repr_ _(self): return self.a # # create instances a = Sample() print "normal", "=>", a b = new.instance(Sample, {}) print "new.instance", "=>", b b._ _init_ _() print "after _ _init_ _", "=>", b c = new.instance(Sample, {"a": "assigned"}) print "new.instance w. dictionary", "=>", c *B*normal => initialised new.instance => default after _ _init_ _ => initialised new.instance w. dictionary => assigned*b* }}} ---- == 1.8. pre 模块 == (已废弃) {{{pre}}} 模块是 1.5.2 中 {{{re}}} 模块调用的实现功能模块. 在当前版本中已废弃. [[#eg-13-8|Example 13-8]] 展示了它的使用. ==== 1.8.0.1. Example 13-8. 使用 pre 模块 ==== {{{ File: pre-example-1.py import pre p = pre.compile("[Python]+") print p.findall("Python is not that bad") *B*['Python', 'not', 'th', 't']*b* }}} ---- == 1.9. sre 模块 == (功能实现模块, 已声明不支持) {{{sre}}} 模块是 {{{re}}} 模块的底层实现. 一般没必要直接使用它, 而且以后版本将不会支持它. [[#eg-13-9|Example 13-9]] 展示了它的使用. ==== 1.9.0.1. Example 13-9. 使用 sre 模块 ==== {{{ File: sre-example-1.py import sre text = "The Bookshop Sketch" # a single character m = sre.match(".", text) if m: print repr("."), "=>", repr(m.group(0)) # and so on, for all 're' examples... *B*'.' => 'T'*b* }}} ---- == 1.10. py_compile 模块 == {{{py_compile}}} 模块用于将 Python 模块编译为字节代码. 它和 Python 的 import 语句行为类似, 不过它接受文件名而不是模块名作为参数. 使用方法如 [[#eg-13-10|Example 13-10]] 所示. ==== 1.10.0.1. Example 13-10. 使用 py_compile 模块 ==== {{{ File: py-compile-example-1.py import py_compile # explicitly compile this module py_compile.compile("py-compile-example-1.py") }}} {{{compileall}}} 模块可以把一个目录树下的所有 Python 文件编译为字节代码. ---- == 1.11. compileall 模块 == {{{compileall}}} 模块用于将给定目录下(以及 Python path )的所有 Python 脚本编译为字节代码. 它也可以作为可执行脚本使用(在 Unix 系统下, Python 安装时会自动调用执行它). 用法参见 [[#eg-13-11|Example 13-11]] . ==== 1.11.0.1. Example 13-11. 使用 compileall 模块编译目录中的所有脚本 ==== {{{ File: compileall-example-1.py import compileall print "This may take a while!" compileall.compile_dir(".", force=1) *B*This may take a while! Listing . ... Compiling .\SimpleAsyncHTTP.py ... Compiling .\aifc-example-1.py ... Compiling .\anydbm-example-1.py ... ...*b* }}} ---- == 1.12. ihooks 模块 == {{{ihooks}}} 模块为替换导入提供了一个框架. 这允许多个导入机制共存. 使用方法参见 [[#eg-13-12|Example 13-12]] . ==== 1.12.0.1. Example 13-12. 使用 ihooks 模块 ==== {{{ File: ihooks-example-1.py import ihooks, imp, os def import_from(filename): "Import module from a named file" loader = ihooks.BasicModuleLoader() path, file = os.path.split(filename) name, ext = os.path.splitext(file) m = loader.find_module_in_dir(name, path) if not m: raise ImportError, name m = loader.load_module(name, m) return m colorsys = import_from("/python/lib/colorsys.py") print colorsys *B**b* }}} ---- == 1.13. linecache 模块 == {{{linecache}}} 模块用于从模块源文件中读取代码. 它会缓存最近访问的模块 (整个源文件). 如 [[#eg-13-13|Example 13-13]] . ==== 1.13.0.1. Example 13-13. 使用 linecache 模块 ==== {{{ File: linecache-example-1.py import linecache print linecache.getline("linecache-example-1.py", 5) *B*print linecache.getline("linecache-example-1.py", 5)*b* }}} {{{traceback}}} 模块使用这个模块实现了对导入操作的跟踪. ---- == 1.14. macurl2path 模块 == (功能实现模块) {{{macurl2path}}} 模块用于 URL 和 Macintosh 文件名 的相互映射. 一般没有必要直接使用它, 请使用 {{{urllib}}} 中的机制. 它的用法参见 [[#eg-13-14|Example 13-14]] . ==== 1.14.0.1. Example 13-14. 使用 macurl2path 模块 ==== {{{ File: macurl2path-example-1.py import macurl2path file = ":my:little:pony" print macurl2path.pathname2url(file) print macurl2path.url2pathname(macurl2path.pathname2url(file)) *B*my/little/pony :my:little:pony*b* }}} ---- == 1.15. nturl2path 模块 == (功能实现模块) {{{nturl2path}}} 模块用于 URL 和 Windows 文件名的 相互映射. 用法参见 [[#eg-13-15|Example 13-15]] . ==== 1.15.0.1. Example 13-15. 使用 nturl2path 模块 ==== {{{ File: nturl2path-example-1.py import nturl2path file = r"c:\my\little\pony" print nturl2path.pathname2url(file) print nturl2path.url2pathname(nturl2path.pathname2url(file)) *B*///C|/my/little/pony C:\my\little\pony*b* }}} 同样地, 请通过 {{{urllib}}} 模块来访问这些函数, 如 [[#eg-13-16|Example 13-16]] 所示. ==== 1.15.0.2. Example 13-16. 通过 urllib 调用 nturl2path 模块 ==== {{{ File: nturl2path-example-2.py import urllib file = r"c:\my\little\pony" print urllib.pathname2url(file) print urllib.url2pathname(urllib.pathname2url(file)) *B*///C|/my/little/pony C:\my\little\pony*b* }}} ---- == 1.16. tokenize 模块 == {{{tokenize}}} 模块将一段 Python 源文件分割成不同的 token . 你可以在代码高亮工具中使用它. 在 [[#eg-13-17|Example 13-17]] 中, 我们分别打印出这些 token . ==== 1.16.0.1. Example 13-17. 使用 tokenize 模块 ==== {{{ File: tokenize-example-1.py import tokenize file = open("tokenize-example-1.py") def handle_token(type, token, (srow, scol), (erow, ecol), line): print "%d,%d-%d,%d:\t%s\t%s" % \ (srow, scol, erow, ecol, tokenize.tok_name[type], repr(token)) tokenize.tokenize( file.readline, handle_token ) *B*1,0-1,6: NAME 'import' 1,7-1,15: NAME 'tokenize' 1,15-1,16: NEWLINE '\012' 2,0-2,1: NL '\012' 3,0-3,4: NAME 'file' 3,5-3,6: OP '=' 3,7-3,11: NAME 'open' 3,11-3,12: OP '(' 3,12-3,35: STRING '"tokenize-example-1.py"' 3,35-3,36: OP ')' 3,36-3,37: NEWLINE '\012' ...*b* }}} 注意这里的 {{{tokenize}}} 函数接受两个可调用对象作为参数: 前一个用于获取新的代码行, 第二个用于在获得每个 token 时调用. ---- == 1.17. keyword 模块 == {{{keyword}}} 模块(参见 [[#eg-13-18|Example 13-18]] )有一个包含当前 Python 版本所使用的关键字的列表. 它还提供了一个字典, 以关键字作为 key , 以一个描述性函数作为 value , 它可用于检查 给定单词是否是 Python 关键字. ==== 1.17.0.1. Example 13-18. 使用 keyword 模块 ==== {{{ File: keyword-example-1.py import keyword name = raw_input("Enter module name: ") if keyword.iskeyword(name): print name, "is a reserved word." print "here's a complete list of reserved words:" print keyword.kwlist *B*Enter module name: assert assert is a reserved word. here's a complete list of reserved words: ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while']*b* }}} ---- == 1.18. parser 模块 == (可选) {{{parser}}} 模块提供了一个到 Python 内建语法分析器和编译器的接口. [[#eg-13-19|Example 13-19]] 将一个简单的表达式编译为一个抽象语法树( abstract syntax tree , AST ), 然后将 AST 转换为一个嵌套列表, 转储树 ( 其中每个节点包含一个语法符号或者是一个 token )中的内容, 将所有数字加上 1 , 最后将列表转回一个代码对象. 至少我认为它是这么做的. ==== 1.18.0.1. Example 13-19. 使用 parser 模块 ==== {{{ File: parser-example-1.py import parser import symbol, token def dump_and_modify(node): name = symbol.sym_name.get(node[0]) if name is None: name = token.tok_name.get(node[0]) print name, for i in range(1, len(node)): item = node[i] if type(item) is type([]): dump_and_modify(item) else: print repr(item) if name == "NUMBER": # increment all numbers! node[i] = repr(int(item)+1) ast = parser.expr("1 + 3") list = ast.tolist() dump_and_modify(list) ast = parser.sequence2ast(list) print eval(parser.compileast(ast)) *B*eval_input testlist test and_test not_test comparison expr xor_expr and_expr shift_expr arith_expr term factor power atom NUMBER '1' PLUS '+' term factor power atom NUMBER '3' NEWLINE '' ENDMARKER '' 6*b* }}} ---- == 1.19. symbol 模块 == {{{symbol}}} 模块包含 Python 语法中的非终止符号. 可能只有你涉及 {{{parser}}} 模块的时候用到它. 用法参见 [[#eg-13-20|Example 13-20]] . ==== 1.19.0.1. Example 13-20. 使用 symbol 模块 ==== {{{ File: symbol-example-1.py import symbol print "print", symbol.print_stmt print "return", symbol.return_stmt *B*print 268 return 274*b* }}} ---- == 1.20. token 模块 == {{{token}}} 模块包含标准 Python tokenizer 所使用的 token 标记. 如 [[#eg-13-21|Example 13-21]] 所示. ==== 1.20.0.1. Example 13-21. 使用 token 模块 ==== {{{ File: token-example-1.py import token print "NUMBER", token.NUMBER print "PLUS", token.STAR print "STRING", token.STRING *B*NUMBER 2 PLUS 16 STRING 3*b* }}} ---- ## moin code generated by txt2tags 2.4 (http://txt2tags.sf.net) ## cmdline: txt2tags -t moin -o moin/chapter13.moin chapter13.t2t