4 from os.path import abspath
9 class Error(EnvironmentError):
16 def ignore_patterns(*patterns):
17 """Function that can be used as copytree() ignore parameter.
19 Patterns is a sequence of glob-style patterns
20 that are used to exclude files"""
21 def _ignore_patterns(path, names):
23 for pattern in patterns:
24 ignored_names.extend(fnmatch.filter(names, pattern))
25 return set(ignored_names)
26 return _ignore_patterns
28 def copytree(src, dst, symlinks=False, ignore=None):
29 """Recursively copy a directory tree using shutil.copy2().
31 The destination directory must not already exist.
32 If exception(s) occur, an Error is raised with a list of reasons.
34 If the optional symlinks flag is true, symbolic links in the
35 source tree result in symbolic links in the destination tree; if
36 it is false, the contents of the files pointed to by symbolic
39 The optional ignore argument is a callable. If given, it
40 is called with the `src` parameter, which is the directory
41 being visited by copytree(), and `names` which is the list of
42 `src` contents, as returned by os.listdir():
44 callable(src, names) -> ignored_names
46 Since copytree() is called recursively, the callable will be
47 called once for each directory that is copied. It returns a
48 list of names relative to the `src` directory that should
51 XXX Consider this example code rather than the ultimate tool.
54 names = os.listdir(src)
55 if ignore is not None:
56 ignored_names = ignore(src, names)
63 if name in ignored_names:
65 srcname = os.path.join(src, name)
66 dstname = os.path.join(dst, name)
68 if symlinks and os.path.islink(srcname):
69 linkto = os.readlink(srcname)
70 os.symlink(linkto, dstname)
71 elif os.path.isdir(srcname):
72 copytree(srcname, dstname, symlinks, ignore)
74 shutil.copy2(srcname, dstname)
75 # XXX What about devices, sockets etc.?
76 except (IOError, os.error), why:
77 errors.append((srcname, dstname, str(why)))
78 # catch the Error from the recursive copytree so that we can
79 # continue with other files
81 errors.extend(err.args[0])
83 shutil.copystat(src, dst)
85 if WindowsError is not None and isinstance(why, WindowsError):
86 # Copying file access times may fail on Windows
89 errors.extend((src, dst, str(why)))