Python 中的標準 errno 系統符號


每種程式語言都具有錯誤處理機制,其中一些錯誤已編碼到編譯器中。在 Python 中,我們有 love,它與一些標準預定義錯誤程式碼相關聯。在本文中,我們將瞭解如何獲取錯誤號以及內建的錯誤程式碼。然後透過一個示例瞭解如何使用錯誤程式碼。

錯誤程式碼

在此程式中,僅列出內建錯誤號和錯誤程式碼。紀念我們使用錯誤模組以及作業系統模組。

示例

 線上演示

import errno
import os
for i in sorted(errno.errorcode):
   print(i,':',os.strerror(i))

輸出

執行以上程式碼,得到以下結果 -

1 : Operation not permitted
2 : No such file or directory
3 : No such process
4 : Interrupted function call
…………
………..

這裡我們演示如何引發並使用區域。我們以 - 沒有這樣的檔案錯誤為例。

示例

 線上演示

try:
   file_name = open('Data.txt')
# 2 is 'No such file or directory'
   except IOError as e:
   if e.errno == 2:
      print(e.strerror)
      print("File to be printed no found")
      # handle exception
   elif e.errno == 9:
      print(e.strerror)
      print("File will not print")

輸出

執行以上程式碼,得到以下結果 -

No such file or directory
File to be printed no found

更新時間: 2020-07-09

389 瀏覽

開啟您的 職業 生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.