Home > python > ignore a specific OSError error

ignore a specific OSError error

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).

Advertisements
  1. Alejandro Martinis
    October 26, 2015 at 15:10

    Thank you very much for this code. It solved a misbehaving script perfectly.

  2. May 4, 2016 at 14:36

    Doesn’t the example code ignore all OSError exceptions, irrespective of error number? I think you’d want to re-raise the error with something like:

        import errno
        import shutil
         
        def my_copy(src, dest):
            try:
                shutil.copy(src, dest)
            except OSError as e:
                if e.errno != errno.ENOTSUP:
                    raise
    
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: