Archive

Posts Tagged ‘exception handling’

ignore a specific OSError error

October 17, 2015 2 comments

Problem
I have a Google Nexus tablet and its file system is available via the MTP protocol. I can access the tablet’s file system in command-line but when I want to copy a file to it with a Python script, I get this error:

  ...
  File "something.py", line 81, in create_in_dest
    shutil.copy(src_long, dest_long)
  File "/usr/lib/python3.5/shutil.py", line 236, in copy
    copymode(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.5/shutil.py", line 138, in copymode
    chmod_func(dst, stat.S_IMODE(st.st_mode))
OSError: [Errno 95] Operation not supported ...

It means that the permissions of the original file cannot be set on the destination file. The file is copied but then this error is raised. If the permissions are not the same, who cares? Not a big deal. So how to ignore this specific error (Errno 95)?

Solution

import errno
import shutil

def my_copy(src, dest):
    try:
        shutil.copy(src, dest)
    except OSError as e:
        if e.errno == 95:
            pass

This error code 95 could also be written as errno.ENOTSUP (it’s a constant in the errno module).

Catch a specific IOError

March 30, 2012 Leave a comment

Problem
If you want to open a non-existing file, you get the following error message: “IOError: [Errno 2] No such file or directory:...“. How to catch this specific IOError? For instance you want to notify the user that the file is missing instead of just saying “an I/O error occurred”.

Solution
Example:

def read_data_file(self):
    try:
        with open(self.data_file) as f:
           return json.load(f)
    except IOError, e:
        if e.errno == errno.ENOENT:
            print "Error: the given file doesn't exist."
            sys.exit(1)

Errno 2 == errno.ENOENT.

This tip is from here.