diff options
author | Guido van Rossum <guido@python.org> | 1998-02-06 21:38:09 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 1998-02-06 21:38:09 (GMT) |
commit | d76732918a12e03e95b753dde2691268592ae0cf (patch) | |
tree | 5cb2f660fd3c0cca33e58c22705f54218c48c02a /Lib | |
parent | a0fec2b5df6827300bf80511a1fd6596e6f71e21 (diff) | |
download | cpython-d76732918a12e03e95b753dde2691268592ae0cf.zip cpython-d76732918a12e03e95b753dde2691268592ae0cf.tar.gz cpython-d76732918a12e03e95b753dde2691268592ae0cf.tar.bz2 |
Added rmtree(), to recursively remove a directory tree.
Code by David Ascher (docstring by me).
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/shutil.py | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/Lib/shutil.py b/Lib/shutil.py index 60c5c6d..2bfe331 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -93,3 +93,35 @@ def copytree(src, dst, symlinks=0): # XXX What about devices, sockets etc.? except (IOError, os.error), why: print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why)) + +def rmtree(path, ignore_errors=0, onerror=None): + """Recursively delete a directory tree. + + If ignore_errors is set, errors are ignored; otherwise, if + onerror is set, it is called to handle the error; otherwise, an + exception is raised. + + """ + cmdtuples = [] + _build_cmdtuple(path, cmdtuples) + for cmd in cmdtuples: + try: + apply(cmd[0], (cmd[1],)) + except: + exc = sys.exc_info() + if ignore_errors: + pass + elif onerror: + onerror(cmd[0], cmd[1], exc) + else: + raise exc[0], (exc[1][0], exc[1][1] + ' removing '+cmd[1]) + +# Helper for rmtree() +def _build_cmdtuple(path, cmdtuples): + for f in os.listdir(path): + real_f = os.path.join(path,f) + if os.path.isdir(real_f) and not os.path.islink(real_f): + _build_cmdtuple(real_f, cmdtuples) + else: + cmdtuples.append(os.remove, real_f) + cmdtuples.append(os.rmdir, path) |