You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

shutil.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """Utility functions for copying files and directory trees.
  2. XXX The functions here don't copy the resource fork or other metadata on Mac.
  3. """
  4. import os
  5. import sys
  6. import stat
  7. __all__ = ["copyfileobj","copyfile","copymode","copystat","copy","copy2",
  8. "copytree","rmtree"]
  9. def copyfileobj(fsrc, fdst, length=16*1024):
  10. """copy data from file-like object fsrc to file-like object fdst"""
  11. while 1:
  12. buf = fsrc.read(length)
  13. if not buf:
  14. break
  15. fdst.write(buf)
  16. def copyfile(src, dst):
  17. """Copy data from src to dst"""
  18. fsrc = None
  19. fdst = None
  20. try:
  21. fsrc = open(src, 'rb')
  22. fdst = open(dst, 'wb')
  23. copyfileobj(fsrc, fdst)
  24. finally:
  25. if fdst:
  26. fdst.close()
  27. if fsrc:
  28. fsrc.close()
  29. def copymode(src, dst):
  30. """Copy mode bits from src to dst"""
  31. if hasattr(os, 'chmod'):
  32. st = os.stat(src)
  33. mode = stat.S_IMODE(st[stat.ST_MODE])
  34. os.chmod(dst, mode)
  35. def copystat(src, dst):
  36. """Copy all stat info (mode bits, atime and mtime) from src to dst"""
  37. st = os.stat(src)
  38. mode = stat.S_IMODE(st[stat.ST_MODE])
  39. if hasattr(os, 'utime'):
  40. os.utime(dst, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
  41. if hasattr(os, 'chmod'):
  42. os.chmod(dst, mode)
  43. def copy(src, dst):
  44. """Copy data and mode bits ("cp src dst").
  45. The destination may be a directory.
  46. """
  47. if os.path.isdir(dst):
  48. dst = os.path.join(dst, os.path.basename(src))
  49. copyfile(src, dst)
  50. copymode(src, dst)
  51. def copy2(src, dst):
  52. """Copy data and all stat info ("cp -p src dst").
  53. The destination may be a directory.
  54. """
  55. if os.path.isdir(dst):
  56. dst = os.path.join(dst, os.path.basename(src))
  57. copyfile(src, dst)
  58. copystat(src, dst)
  59. def copytree(src, dst, symlinks=0):
  60. """Recursively copy a directory tree using copy2().
  61. The destination directory must not already exist.
  62. Error are reported to standard output.
  63. If the optional symlinks flag is true, symbolic links in the
  64. source tree result in symbolic links in the destination tree; if
  65. it is false, the contents of the files pointed to by symbolic
  66. links are copied.
  67. XXX Consider this example code rather than the ultimate tool.
  68. """
  69. names = os.listdir(src)
  70. os.mkdir(dst)
  71. for name in names:
  72. srcname = os.path.join(src, name)
  73. dstname = os.path.join(dst, name)
  74. try:
  75. if symlinks and os.path.islink(srcname):
  76. linkto = os.readlink(srcname)
  77. os.symlink(linkto, dstname)
  78. elif os.path.isdir(srcname):
  79. copytree(srcname, dstname, symlinks)
  80. else:
  81. copy2(srcname, dstname)
  82. # XXX What about devices, sockets etc.?
  83. except (IOError, os.error), why:
  84. print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))
  85. def rmtree(path, ignore_errors=0, onerror=None):
  86. """Recursively delete a directory tree.
  87. If ignore_errors is set, errors are ignored; otherwise, if
  88. onerror is set, it is called to handle the error; otherwise, an
  89. exception is raised.
  90. """
  91. cmdtuples = []
  92. _build_cmdtuple(path, cmdtuples)
  93. for cmd in cmdtuples:
  94. try:
  95. apply(cmd[0], (cmd[1],))
  96. except:
  97. exc = sys.exc_info()
  98. if ignore_errors:
  99. pass
  100. elif onerror:
  101. onerror(cmd[0], cmd[1], exc)
  102. else:
  103. raise exc[0], (exc[1][0], exc[1][1] + ' removing '+cmd[1])
  104. # Helper for rmtree()
  105. def _build_cmdtuple(path, cmdtuples):
  106. for f in os.listdir(path):
  107. real_f = os.path.join(path,f)
  108. if os.path.isdir(real_f) and not os.path.islink(real_f):
  109. _build_cmdtuple(real_f, cmdtuples)
  110. else:
  111. cmdtuples.append((os.remove, real_f))
  112. cmdtuples.append((os.rmdir, path))