本文介绍了FAT文件系统(Ubuntu)上的Python shutil.copy失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:在Linux中使用shutil.copy()将文件复制到FAT16挂载的文件系统失败(Python 2.7.x).该故障是由shutil内部错误引起的,实际上是在shutil.chmod上失败,似乎已执行了shutil.copy.

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也失败,因为FAT不支持权限.

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. 使用复制文件-不理想,因为它需要完整路径,不仅是目标目录,而且是可行的
  2. 执行shell cp复制文件
  3. 编写自己的复制功能,不尝试更改文件模式

在Python或FAT挂载选项中是否可以解决此问题?现在,我通过执行mount -t vfat -o umask = 000/dev/loop0/mnt/foo

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

捕获异常无济于事,因为异常发生在shutil.copy内,当closeil.copy()从shutdownil.chmod()捕获IOException时,似乎将目标文件删除,然后再将IOException传递给调用函数.

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.

任何想法,还是我应该从1-3个中选择一个?

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

Hannu

推荐答案

在这种情况下,我作弊.

Well I cheat in this case.

如果我知道目标是chmod失败的文件系统,则只需使用del os.chmod从os包中删除chmod方法,这将使复制成功.

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

现在,您可以执行复制而不会在chmod上失败.然后,我们通过将属性分配回去来重新启用它.

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

这篇关于FAT文件系统(Ubuntu)上的Python shutil.copy失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 08:09