Python errno Module

The errno module in Python provides standard error codes that are commonly used in operating systems. These error codes are used to indicate different error conditions, making it easier to handle errors in a consistent manner.

Table of Contents

  1. Introduction
  2. Key Constants
    • errno.EPERM
    • errno.ENOENT
    • errno.ESRCH
    • errno.EINTR
    • errno.EIO
    • errno.ENXIO
    • errno.E2BIG
    • errno.ENOEXEC
    • errno.EBADF
    • errno.ECHILD
    • errno.EAGAIN
    • errno.ENOMEM
    • errno.EACCES
    • errno.EFAULT
    • errno.ENOTBLK
    • errno.EBUSY
    • errno.EEXIST
    • errno.EXDEV
    • errno.ENODEV
    • errno.ENOTDIR
    • errno.EISDIR
    • errno.EINVAL
    • errno.ENFILE
    • errno.EMFILE
    • errno.ENOTTY
    • errno.ETXTBSY
    • errno.EFBIG
    • errno.ENOSPC
    • errno.ESPIPE
    • errno.EROFS
    • errno.EMLINK
    • errno.EPIPE
    • errno.EDOM
    • errno.ERANGE
  3. Examples
    • Handling File Not Found Error
    • Handling Permission Denied Error
    • Checking Error Codes
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The errno module defines symbolic error codes corresponding to different error conditions. These codes are used to identify specific errors when exceptions are raised, particularly OSError exceptions. Using these symbolic names rather than raw numbers makes the code more readable and maintainable.

Key Constants

errno.EPERM

Operation not permitted.

errno.ENOENT

No such file or directory.

errno.ESRCH

No such process.

errno.EINTR

Interrupted system call.

errno.EIO

Input/output error.

errno.ENXIO

No such device or address.

errno.E2BIG

Argument list too long.

errno.ENOEXEC

Exec format error.

errno.EBADF

Bad file descriptor.

errno.ECHILD

No child processes.

errno.EAGAIN

Resource temporarily unavailable.

errno.ENOMEM

Out of memory.

errno.EACCES

Permission denied.

errno.EFAULT

Bad address.

errno.ENOTBLK

Block device required.

errno.EBUSY

Device or resource busy.

errno.EEXIST

File exists.

errno.EXDEV

Cross-device link.

errno.ENODEV

No such device.

errno.ENOTDIR

Not a directory.

errno.EISDIR

Is a directory.

errno.EINVAL

Invalid argument.

errno.ENFILE

File table overflow.

errno.EMFILE

Too many open files.

errno.ENOTTY

Not a typewriter.

errno.ETXTBSY

Text file busy.

errno.EFBIG

File too large.

errno.ENOSPC

No space left on device.

errno.ESPIPE

Illegal seek.

errno.EROFS

Read-only file system.

errno.EMLINK

Too many links.

errno.EPIPE

Broken pipe.

errno.EDOM

Math argument out of domain of function.

errno.ERANGE

Result too large.

Examples

Handling File Not Found Error

import errno
import os

try:
    os.remove('non_existent_file.txt')
except OSError as e:
    if e.errno == errno.ENOENT:
        print("Error: No such file or directory")
    else:
        print(f"Error: {e.strerror}")

Output:

Error: No such file or directory

Handling Permission Denied Error

import errno
import os

try:
    with open('/root/protected_file.txt', 'r') as file:
        content = file.read()
except OSError as e:
    if e.errno == errno.EACCES:
        print("Error: Permission denied")
    else:
        print(f"Error: {e.strerror}")

Output:

Error: Permission denied

Checking Error Codes

import errno
import os

def check_error(e):
    if e.errno == errno.EPERM:
        print("Operation not permitted")
    elif e.errno == errno.ENOENT:
        print("No such file or directory")
    elif e.errno == errno.EIO:
        print("Input/output error")
    else:
        print(f"Error: {e.strerror}")

try:
    os.remove('non_existent_file.txt')
except OSError as e:
    check_error(e)

Output:

No such file or directory

Real-World Use Case

Robust File Handling

In a real-world application, handling files may encounter various errors. Using the errno module, you can provide specific error messages and handle different error conditions appropriately.

import errno
import os

def delete_file(filepath):
    try:
        os.remove(filepath)
    except OSError as e:
        if e.errno == errno.ENOENT:
            print(f"Error: The file '{filepath}' does not exist.")
        elif e.errno == errno.EACCES:
            print(f"Error: Permission denied to delete '{filepath}'.")
        elif e.errno == errno.EBUSY:
            print(f"Error: The file '{filepath}' is currently in use.")
        else:
            print(f"Error: {e.strerror}")

delete_file('non_existent_file.txt')
delete_file('/root/protected_file.txt')
delete_file('file_in_use.txt')

Output:

Error: The file 'non_existent_file.txt' does not exist.
Error: Permission denied to delete '/root/protected_file.txt'.
Error: The file 'file_in_use.txt' is currently in use.

Conclusion

The errno module in Python provides symbolic names for standard error codes, making error handling more consistent and readable. It is particularly useful for handling OSError exceptions, allowing you to write robust and user-friendly error messages.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare