Python shutil.copy not working on FAT file systems (Ubuntu)

Problem: Using shutil.copy () to copy a file to the FAT16 file system on Linux fails (Python 2.7.x). The error is an internal error in the internal interface, and it actually happens on shutil.chmod, which appears to be executing shutil.copy.

The chmod shell also crashes because permissions are not supported in FAT.

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

  • Using copyfile is not ideal as it requires the full path, not just the destination directory, but executable
  • Run cp shell to copy files
  • Write your own copy function that does not try to change file modes.

Is there a way around this in Python OR in the FAT mount settings? Now I mount the file system inside my program by running mount -t vfat -o umask = 000 / dev / loop0 / mnt / foo

Catching an exception does not help, since the exception occurs inside shutil.copy and shutil.copy (), it seems to delete the target file when it catches an IOException from shutil.chmod () before passing an IOException to the calling function.

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

Hannah

+6
source share
2 answers

Well, I am cheating in this case.

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

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

Now it allows you to make a copy without failing on chmod. Then we turn it back on by assigning the attribute back.

 >>> setattr(os, 'chmod', foo) >>> print hasattr(os, 'chmod') True 
+5
source

Use shutil.copyfile , this does not require the full path.

Removing os.chmod all over the world is not a good idea.

 $ mkdir folder $ touch folder/a $ python2.7 -c 'import shutil; shutil.copyfile("folder/a","folder/b")' $ ls -rthla folder/ total 0 drwxr-xr-x+ Apr 17 12:49 ../ -rw-r--r-- Apr 17 12:49 a -rw-r--r-- Apr 17 12:50 b drwxr-xr-x+ Apr 17 12:50 ./ 

As you can see in the python source code for shutil ( /usr/lib/python2.7/shutil.py ), there is no path in the copy source code (relative / absolute), the src variable is directly passed as the copyfile argument.

 def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst) 
0
source

Source: https://habr.com/ru/post/958202/


All Articles