Python os.strerror() - 获取与错误代码对应的错误消息

Python os.strerror()

os模块中的所有函数在文件名和路径无效或不可访问,或其他具有正确类型但操作系统不接受的参数时都会引发OSError。

Python中的os.strerror()方法用于获取与错误代码对应的错误消息

语法:os.strerror(code)

参数:

code:表示错误码的整数值

返回类型:该方法返回一个字符串,表示与指定错误码对应的错误消息。

示例1

使用 os.strerror() 方法

# Python program to explain os.strerror() method 
    
# importing os module 
import os
  
# Get the error message 
# corresponding to 
# error code 1
code = 1
error = os.strerror(code)
  
# Print the error message 
# corresponding to 
# error code 1
print("Error message corresponding to error code % d:" % code, error)
  
# Get the error message 
# corresponding to 
# error code 5
code = 5
error = os.strerror(code)
  
# Print the error message 
# corresponding to 
# error code 5
print("Error message corresponding to error code % d:" % code, error)

输出:

Error message corresponding to error code 1: Operation not permitted
Error Message corresponding to error code 5: Input/output error

示例2

打印前20个错误

# Python program to explain os.strerror() method 
    
# importing os module 
import os
  
# Get the error message 
# corresponding to the
# first 20 error codes
n = 20
  
for i in range(1, n + 1)
    error = os.strerror(code)
    print("Error code % d:" % i, error)

输出:

Error code 1: Operation not permitted
Error code 2: No such file or directory
Error code 3: No such process
Error code 4: Interrupted system call
Error code 5: Input/output error
Error code 6: No such device or address
Error code 7: Argument list too long
Error code 8: Exec format error
Error code 9: Bad file descriptor
Error code 10: No child processes
Error code 11: Resource temporarily unavailable
Error code 12: Cannot allocate memory
Error code 13: Permission denied
Error code 14: Bad address
Error code 15: Block device required
Error code 16: Device or resource busy
Error code 17: File exists
Error code 18: Invalid cross-device link
Error code 19: No such device
Error code 20: Not a directory

示例3

检查错误消息以查找无效的错误代码

# Python program to explain os.strerror() method 
    
  
# importing os module 
import os
  
# Get the error message 
# corresponding to 
# error code 200
code = 200
error = os.strerror(code)
  
# Print the error message 
# corresponding to 
# error code 200
print("Error message corresponding to error code % d:" % code, error)
  
  
# Get the error message 
# corresponding to 
# error code 300
code = 300
error = os.strerror(code)
  
# Print the error message 
# corresponding to 
# error code 300
print("Error message corresponding to error code % d:" % code, error)
  
# os.strerror() will return
# An unknown error
# in case specified code
# is invalid

输出:

Error message corresponding to error code 200: Unknown error 200
Error message corresponding to error code 300: Unknown error 300

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程