6

Python's shutil.copytree is not very flexible; what is the simplest way to add support for ignoring permissions while copying in copytree (without having to re-write its implementation)?

Otherwise, copytree fails like this:

(…)”[Errno 45] Operation not supported: ‘/path/foo/bar’”
Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187

3 Answers3

5

Not thread-safe (or advisable in general) but OK for a throwaway script:

import shutil

_orig_copystat = shutil.copystat
shutil.copystat = lambda x, y: x

shutil.copytree(src, dst)

shutil.copystat = _orig_copystat
Jamie
  • 7,635
  • 4
  • 23
  • 16
3

You have shutil.py in your standard Python distribution (on Ubuntu, mine is under /usr/lib/python2.6 for instance; Windows might be C:\Python26\lib?). The copytree function is only 38 lines long (34 if you don't count comments), and the end of the docstring explicitly states:

XXX Consider this example code rather than the ultimate tool.

So the simplest way really would be to change/add a couple lines to copytree, or find another library, to be honest.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
1

In Python 3.2 and higher, there's now a built-in way to do this. shutil.copytree accepts a custom file copy function as an argument. You can use that to change it from the default file copy function (shutil.copy2) to one that doesn't copy permissions like shutil.copy:

shutil.copytree(src, dst, copy_function=shutil.copy)
  • 3
    This will only work for files since directory permissions are not copied with the copy_function. They are mirrored explicitly with shutil.copystat() instead. – cm101 Apr 01 '21 at 17:03