在Python中处理 OSError 异常
让我们看看如何在Python中处理 OSError 异常。 OSError是Python中的内置异常,用作os模块的错误类,当特定于 os 的系统函数返回与系统相关的错误时引发,包括 I/O 失败,例如“找不到文件”或“磁盘已满”。
以下是 OSError 的示例:
Python
# Importing os module
import os
# os.ttyname() method in Python is used to get the terminal
# device associated with the specified file descriptor.
# and raises an exception if the specified file descriptor
# is not associated with any terminal device.
print(os.ttyname(1))
Python
# importing os module
import os
# create a pipe using os.pipe() method
# it will return a pair of
# file descriptors (r, w) usable for
# reading and writing, respectively.
r, w = os.pipe()
# (using exception handling technique)
# try to get the terminal device associated
# with the file descriptor r or w
try :
print(os.ttyname(r))
except OSError as error :
print(error)
print("File descriptor is not associated with any terminal device")
输出 :
OSError: [Errno 25] Inappropriate ioctl for device
我们可以使用 try...except 语句来处理 ODError 异常。
Python
# importing os module
import os
# create a pipe using os.pipe() method
# it will return a pair of
# file descriptors (r, w) usable for
# reading and writing, respectively.
r, w = os.pipe()
# (using exception handling technique)
# try to get the terminal device associated
# with the file descriptor r or w
try :
print(os.ttyname(r))
except OSError as error :
print(error)
print("File descriptor is not associated with any terminal device")
输出 :
[Errno 25] Inappropriate ioctl for device
File descriptor is not associated with any terminal device