📜  Python中的EnvironmentError异常

📅  最后修改于: 2022-05-13 01:55:22.464000             🧑  作者: Mango

Python中的EnvironmentError异常

EnvironmentError是来自Python外部(操作系统、文件系统等)的错误的基类。它是IOErrorOSError异常的父类。

  1. 异常 IOError – 当 I/O 操作(当文件对象的方法)失败时引发。例如“找不到文件”或“磁盘已满”。
  2. 异常 OSError – 当函数返回与系统相关的错误时引发。

IOError 或 OSError 的任何示例也应该是 Environment Error 的示例。

示例 1:

Python3
# importing the module
import sys
  
try:
    # an invalid path
    file = open("GeeksforGeeks.txt", 'r')
except Exception as e:
    print(e)
    print(sys.exc_info()[0])


Python3
# importing the module
import os
import sys
  
try:
    for i in range(7):
        print(i)
        print(os.ttyname(i))
except Exception as e:
    print(e)
    print(sys.exc_info()[0])


Python3
# importing the module
import sys
import os
  
try:
    # an invalid path
    os.rmdir('GEEKS')
except Exception as e:
    print(e)
    print(sys.exc_info()[0])


输出
[Errno 2] No such file or directory: 'GeeksforGeeks.txt'

示例 2:

Python3

# importing the module
import os
import sys
  
try:
    for i in range(7):
        print(i)
        print(os.ttyname(i))
except Exception as e:
    print(e)
    print(sys.exc_info()[0])
输出
0
[Errno 25] Inappropriate ioctl for device

示例 3:

Python3

# importing the module
import sys
import os
  
try:
    # an invalid path
    os.rmdir('GEEKS')
except Exception as e:
    print(e)
    print(sys.exc_info()[0])
输出
[Errno 2] No such file or directory: 'GEEKS'