==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 ```