==errno 模块== ``errno`` 模块定义了许多的符号错误码, 比如 ``ENOENT`` ("没有该目录入口") 以及 ``EPERM`` ("权限被拒绝"). 它还提供了一个映射到对应平台数字错误代码的字典. [Example 2-21 #eg-2-21] 展示了如何使用 ``errno`` 模块. 在大多情况下, //IOError// 异常会提供一个二元元组, 包含对应数值错误代码和一个说明字符串. 如果你需要区分不同的错误代码, 那么最好在可能的地方使用符号名称. ====Example 2-21. 使用 errno 模块====[eg-2-21] ``` File: errno-example-1.py import errno try: fp = open("no.such.file") except IOError, (error, message): if error == errno.ENOENT: print "no such file" elif error == errno.EPERM: print "permission denied" else: print message *B*no such file*b* ``` [Example 2-22 #eg-2-22] 绕了些无用的弯子, 不过它很好地说明了如何使用 ``errorcode`` 字典把数字错误码映射到符号名称( symbolic name ). ====Example 2-22. 使用 errorcode 字典====[eg-2-22] ``` File: errno-example-2.py import errno try: fp = open("no.such.file") except IOError, (error, message): print error, repr(message) print errno.errorcode[error] # 2 'No such file or directory' # ENOENT ```