Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python shutil.copy fails on FAT file systems (Ubuntu)

Problem: Using shutil.copy() to copy a file to a FAT16 mounted filesystem in Linux fails (Python 2.7.x). The failure is shutil internal error and failing actually on shutil.chmod, which shutil.copy seems to execute.

Shell chmod fails, too, as permissions are not supported in FAT.

Questions: Is there any neat way around this? I know I have several options, for example:

  1. Use copyfile - not ideal as it requires full path, not just target directory, but doable
  2. Execute shell cp to copy files
  3. Write own copy function that doesn't try to change file modes

Is there a way around this in Python OR in FAT mount options? I now mount the filesystem inside my program by executing mount -t vfat -o umask=000 /dev/loop0 /mnt/foo

Catching the exception doesn't help, as the exception happens inside shutil.copy and shutil.copy() seems to delete the target file when it catches IOException from shutil.chmod(), before passing IOException to the calling function.

Any ideas, or should I just choose one from 1-3?

Hannu

like image 474
Hannu Avatar asked Nov 16 '13 15:11

Hannu


1 Answers

Well I cheat in this case.

If I know that the target is a file system where chmod fails, I simply delete the chmod method from the os package using del os.chmod, and this allows the copy to succeed.

>>> import os
>>> print hasattr(os, 'chmod')
True
>>> foo = os.chmod
>>> del os.chmod
>>> print hasattr(os, 'chmod')
False

This now allows you to perform the copy without failing on the chmod. Then we re-enable it by assigning the attribute back.

>>> setattr(os, 'chmod', foo)
>>> print hasattr(os, 'chmod')
True
like image 158
Petesh Avatar answered Sep 21 '22 06:09

Petesh