Back to index

python3.2  3.2.2
Classes | Functions | Variables
shutil Namespace Reference

Classes

class  Error
class  SpecialFileError
class  ExecError
class  ReadError
class  RegistryError

Functions

def copyfileobj
def _samefile
def copyfile
def copymode
def copystat
def copy
def copy2
def ignore_patterns
def copytree
def rmtree
def _basename
def move
def _destinsrc
def _get_gid
def _get_uid
def _make_tarball
def _call_external_zip
def _make_zipfile
def get_archive_formats
def register_archive_format
def unregister_archive_format
def make_archive
def get_unpack_formats
def _check_unpack_options
def register_unpack_format
def unregister_unpack_format
def _ensure_directory
def _unpack_zipfile
def _unpack_tarfile
def _find_unpack_format
def unpack_archive

Variables

 _BZ2_SUPPORTED = True
 getpwnam = None
 getgrnam = None
list __all__
 WindowsError = None
dictionary _ARCHIVE_FORMATS
dictionary _UNPACK_FORMATS

Detailed Description

Utility functions for copying and archiving files and directory trees.

XXX The functions here don't copy the resource fork or other metadata on Mac.

Class Documentation

class shutil::Error

Definition at line 39 of file shutil.py.

class shutil::SpecialFileError
Raised when trying to do a kind of operation (e.g. copying) which is
not supported on a special file (e.g. a named pipe)

Definition at line 42 of file shutil.py.

class shutil::ExecError
Raised when a command could not be executed

Definition at line 46 of file shutil.py.

class shutil::ReadError
Raised when an archive cannot be read

Definition at line 49 of file shutil.py.


Function Documentation

def shutil._basename (   path) [private]

Definition at line 290 of file shutil.py.

00290 
00291 def _basename(path):
00292     # A basename() variant which first strips the trailing slash, if present.
00293     # Thus we always get the last component of the path, even for directories.
00294     return os.path.basename(path.rstrip(os.path.sep))

Here is the caller graph for this function:

def shutil._call_external_zip (   base_dir,
  zip_filename,
  verbose = False,
  dry_run = False 
) [private]

Definition at line 430 of file shutil.py.

00430 
00431 def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
00432     # XXX see if we want to keep an external call here
00433     if verbose:
00434         zipoptions = "-r"
00435     else:
00436         zipoptions = "-rq"
00437     from distutils.errors import DistutilsExecError
00438     from distutils.spawn import spawn
00439     try:
00440         spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
00441     except DistutilsExecError:
00442         # XXX really should distinguish between "couldn't find
00443         # external 'zip' command" and "zip failed".
00444         raise ExecError("unable to create zip file '%s': "
00445             "could neither import the 'zipfile' module nor "
00446             "find a standalone zip utility") % zip_filename

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil._check_unpack_options (   extensions,
  function,
  extra_args 
) [private]
Checks what gets registered as an unpacker.

Definition at line 605 of file shutil.py.

00605 
00606 def _check_unpack_options(extensions, function, extra_args):
00607     """Checks what gets registered as an unpacker."""
00608     # first make sure no other unpacker is registered for this extension
00609     existing_extensions = {}
00610     for name, info in _UNPACK_FORMATS.items():
00611         for ext in info[0]:
00612             existing_extensions[ext] = name
00613 
00614     for extension in extensions:
00615         if extension in existing_extensions:
00616             msg = '%s is already registered for "%s"'
00617             raise RegistryError(msg % (extension,
00618                                        existing_extensions[extension]))
00619 
00620     if not isinstance(function, collections.Callable):
00621         raise TypeError('The registered function must be a callable')
00622 

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil._destinsrc (   src,
  dst 
) [private]

Definition at line 335 of file shutil.py.

00335 
00336 def _destinsrc(src, dst):
00337     src = abspath(src)
00338     dst = abspath(dst)
00339     if not src.endswith(os.path.sep):
00340         src += os.path.sep
00341     if not dst.endswith(os.path.sep):
00342         dst += os.path.sep
00343     return dst.startswith(src)

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil._ensure_directory (   path) [private]
Ensure that the parent directory of `path` exists

Definition at line 649 of file shutil.py.

00649 
00650 def _ensure_directory(path):
00651     """Ensure that the parent directory of `path` exists"""
00652     dirname = os.path.dirname(path)
00653     if not os.path.isdir(dirname):
00654         os.makedirs(dirname)

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil._find_unpack_format (   filename) [private]

Definition at line 715 of file shutil.py.

00715 
00716 def _find_unpack_format(filename):
00717     for name, info in _UNPACK_FORMATS.items():
00718         for extension in info[0]:
00719             if filename.endswith(extension):
00720                 return name
00721     return None

Here is the caller graph for this function:

def shutil._get_gid (   name) [private]
Returns a gid, given a group name.

Definition at line 344 of file shutil.py.

00344 
00345 def _get_gid(name):
00346     """Returns a gid, given a group name."""
00347     if getgrnam is None or name is None:
00348         return None
00349     try:
00350         result = getgrnam(name)
00351     except KeyError:
00352         result = None
00353     if result is not None:
00354         return result[2]
00355     return None

Here is the caller graph for this function:

def shutil._get_uid (   name) [private]
Returns an uid, given a user name.

Definition at line 356 of file shutil.py.

00356 
00357 def _get_uid(name):
00358     """Returns an uid, given a user name."""
00359     if getpwnam is None or name is None:
00360         return None
00361     try:
00362         result = getpwnam(name)
00363     except KeyError:
00364         result = None
00365     if result is not None:
00366         return result[2]
00367     return None

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil._make_tarball (   base_name,
  base_dir,
  compress = "gzip",
  verbose = 0,
  dry_run = 0,
  owner = None,
  group = None,
  logger = None 
) [private]
Create a (possibly compressed) tar file from all the files under
'base_dir'.

'compress' must be "gzip" (the default), "bzip2", or None.

'owner' and 'group' can be used to define an owner and a group for the
archive that is being built. If not provided, the current owner and group
will be used.

The output tar file will be named 'base_name' +  ".tar", possibly plus
the appropriate compression extension (".gz", or ".bz2").

Returns the output filename.

Definition at line 369 of file shutil.py.

00369 
00370                   owner=None, group=None, logger=None):
00371     """Create a (possibly compressed) tar file from all the files under
00372     'base_dir'.
00373 
00374     'compress' must be "gzip" (the default), "bzip2", or None.
00375 
00376     'owner' and 'group' can be used to define an owner and a group for the
00377     archive that is being built. If not provided, the current owner and group
00378     will be used.
00379 
00380     The output tar file will be named 'base_name' +  ".tar", possibly plus
00381     the appropriate compression extension (".gz", or ".bz2").
00382 
00383     Returns the output filename.
00384     """
00385     tar_compression = {'gzip': 'gz', None: ''}
00386     compress_ext = {'gzip': '.gz'}
00387 
00388     if _BZ2_SUPPORTED:
00389         tar_compression['bzip2'] = 'bz2'
00390         compress_ext['bzip2'] = '.bz2'
00391 
00392     # flags for compression program, each element of list will be an argument
00393     if compress is not None and compress not in compress_ext.keys():
00394         raise ValueError("bad value for 'compress', or compression format not "
00395                          "supported : {0}".format(compress))
00396 
00397     archive_name = base_name + '.tar' + compress_ext.get(compress, '')
00398     archive_dir = os.path.dirname(archive_name)
00399 
00400     if not os.path.exists(archive_dir):
00401         if logger is not None:
00402             logger.info("creating %s" % archive_dir)
00403         if not dry_run:
00404             os.makedirs(archive_dir)
00405 
00406     # creating the tarball
00407     if logger is not None:
00408         logger.info('Creating tar archive')
00409 
00410     uid = _get_uid(owner)
00411     gid = _get_gid(group)
00412 
00413     def _set_uid_gid(tarinfo):
00414         if gid is not None:
00415             tarinfo.gid = gid
00416             tarinfo.gname = group
00417         if uid is not None:
00418             tarinfo.uid = uid
00419             tarinfo.uname = owner
00420         return tarinfo
00421 
00422     if not dry_run:
00423         tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
00424         try:
00425             tar.add(base_dir, filter=_set_uid_gid)
00426         finally:
00427             tar.close()
00428 
00429     return archive_name

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil._make_zipfile (   base_name,
  base_dir,
  verbose = 0,
  dry_run = 0,
  logger = None 
) [private]
Create a zip file from all the files under 'base_dir'.

The output zip file will be named 'base_name' + ".zip".  Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path).  If neither tool is
available, raises ExecError.  Returns the name of the output zip
file.

Definition at line 447 of file shutil.py.

00447 
00448 def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
00449     """Create a zip file from all the files under 'base_dir'.
00450 
00451     The output zip file will be named 'base_name' + ".zip".  Uses either the
00452     "zipfile" Python module (if available) or the InfoZIP "zip" utility
00453     (if installed and found on the default search path).  If neither tool is
00454     available, raises ExecError.  Returns the name of the output zip
00455     file.
00456     """
00457     zip_filename = base_name + ".zip"
00458     archive_dir = os.path.dirname(base_name)
00459 
00460     if not os.path.exists(archive_dir):
00461         if logger is not None:
00462             logger.info("creating %s", archive_dir)
00463         if not dry_run:
00464             os.makedirs(archive_dir)
00465 
00466     # If zipfile module is not available, try spawning an external 'zip'
00467     # command.
00468     try:
00469         import zipfile
00470     except ImportError:
00471         zipfile = None
00472 
00473     if zipfile is None:
00474         _call_external_zip(base_dir, zip_filename, verbose, dry_run)
00475     else:
00476         if logger is not None:
00477             logger.info("creating '%s' and adding '%s' to it",
00478                         zip_filename, base_dir)
00479 
00480         if not dry_run:
00481             zip = zipfile.ZipFile(zip_filename, "w",
00482                                   compression=zipfile.ZIP_DEFLATED)
00483 
00484             for dirpath, dirnames, filenames in os.walk(base_dir):
00485                 for name in filenames:
00486                     path = os.path.normpath(os.path.join(dirpath, name))
00487                     if os.path.isfile(path):
00488                         zip.write(path, path)
00489                         if logger is not None:
00490                             logger.info("adding '%s'", path)
00491             zip.close()
00492 
00493     return zip_filename

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil._samefile (   src,
  dst 
) [private]

Definition at line 70 of file shutil.py.

00070 
00071 def _samefile(src, dst):
00072     # Macintosh, Unix.
00073     if hasattr(os.path, 'samefile'):
00074         try:
00075             return os.path.samefile(src, dst)
00076         except OSError:
00077             return False
00078 
00079     # All other platforms: check for same pathname.
00080     return (os.path.normcase(os.path.abspath(src)) ==
00081             os.path.normcase(os.path.abspath(dst)))

Here is the caller graph for this function:

def shutil._unpack_tarfile (   filename,
  extract_dir 
) [private]
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`

Definition at line 692 of file shutil.py.

00692 
00693 def _unpack_tarfile(filename, extract_dir):
00694     """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
00695     """
00696     try:
00697         tarobj = tarfile.open(filename)
00698     except tarfile.TarError:
00699         raise ReadError(
00700             "%s is not a compressed or uncompressed tar file" % filename)
00701     try:
00702         tarobj.extractall(extract_dir)
00703     finally:
00704         tarobj.close()

def shutil._unpack_zipfile (   filename,
  extract_dir 
) [private]
Unpack zip `filename` to `extract_dir`

Definition at line 655 of file shutil.py.

00655 
00656 def _unpack_zipfile(filename, extract_dir):
00657     """Unpack zip `filename` to `extract_dir`
00658     """
00659     try:
00660         import zipfile
00661     except ImportError:
00662         raise ReadError('zlib not supported, cannot unpack this archive.')
00663 
00664     if not zipfile.is_zipfile(filename):
00665         raise ReadError("%s is not a zip file" % filename)
00666 
00667     zip = zipfile.ZipFile(filename)
00668     try:
00669         for info in zip.infolist():
00670             name = info.filename
00671 
00672             # don't extract absolute paths or ones with .. in them
00673             if name.startswith('/') or '..' in name:
00674                 continue
00675 
00676             target = os.path.join(extract_dir, *name.split('/'))
00677             if not target:
00678                 continue
00679 
00680             _ensure_directory(target)
00681             if not name.endswith('/'):
00682                 # file
00683                 data = zip.read(info.filename)
00684                 f = open(target,'wb')
00685                 try:
00686                     f.write(data)
00687                 finally:
00688                     f.close()
00689                     del data
00690     finally:
00691         zip.close()

Here is the call graph for this function:

def shutil.copy (   src,
  dst 
)
Copy data and mode bits ("cp src dst").

The destination may be a directory.

Definition at line 125 of file shutil.py.

00125 
00126 def copy(src, dst):
00127     """Copy data and mode bits ("cp src dst").
00128 
00129     The destination may be a directory.
00130 
00131     """
00132     if os.path.isdir(dst):
00133         dst = os.path.join(dst, os.path.basename(src))
00134     copyfile(src, dst)
00135     copymode(src, dst)

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.copy2 (   src,
  dst 
)
Copy data and all stat info ("cp -p src dst").

The destination may be a directory.

Definition at line 136 of file shutil.py.

00136 
00137 def copy2(src, dst):
00138     """Copy data and all stat info ("cp -p src dst").
00139 
00140     The destination may be a directory.
00141 
00142     """
00143     if os.path.isdir(dst):
00144         dst = os.path.join(dst, os.path.basename(src))
00145     copyfile(src, dst)
00146     copystat(src, dst)

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.copyfile (   src,
  dst 
)
Copy data from src to dst

Definition at line 82 of file shutil.py.

00082 
00083 def copyfile(src, dst):
00084     """Copy data from src to dst"""
00085     if _samefile(src, dst):
00086         raise Error("`%s` and `%s` are the same file" % (src, dst))
00087 
00088     for fn in [src, dst]:
00089         try:
00090             st = os.stat(fn)
00091         except OSError:
00092             # File most likely does not exist
00093             pass
00094         else:
00095             # XXX What about other special files? (sockets, devices...)
00096             if stat.S_ISFIFO(st.st_mode):
00097                 raise SpecialFileError("`%s` is a named pipe" % fn)
00098 
00099     with open(src, 'rb') as fsrc:
00100         with open(dst, 'wb') as fdst:
00101             copyfileobj(fsrc, fdst)

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.copyfileobj (   fsrc,
  fdst,
  length = 16*1024 
)
copy data from file-like object fsrc to file-like object fdst

Definition at line 62 of file shutil.py.

00062 
00063 def copyfileobj(fsrc, fdst, length=16*1024):
00064     """copy data from file-like object fsrc to file-like object fdst"""
00065     while 1:
00066         buf = fsrc.read(length)
00067         if not buf:
00068             break
00069         fdst.write(buf)

Here is the caller graph for this function:

def shutil.copymode (   src,
  dst 
)
Copy mode bits from src to dst

Definition at line 102 of file shutil.py.

00102 
00103 def copymode(src, dst):
00104     """Copy mode bits from src to dst"""
00105     if hasattr(os, 'chmod'):
00106         st = os.stat(src)
00107         mode = stat.S_IMODE(st.st_mode)
00108         os.chmod(dst, mode)

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.copystat (   src,
  dst 
)
Copy all stat info (mode bits, atime, mtime, flags) from src to dst

Definition at line 109 of file shutil.py.

00109 
00110 def copystat(src, dst):
00111     """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
00112     st = os.stat(src)
00113     mode = stat.S_IMODE(st.st_mode)
00114     if hasattr(os, 'utime'):
00115         os.utime(dst, (st.st_atime, st.st_mtime))
00116     if hasattr(os, 'chmod'):
00117         os.chmod(dst, mode)
00118     if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
00119         try:
00120             os.chflags(dst, st.st_flags)
00121         except OSError as why:
00122             if (not hasattr(errno, 'EOPNOTSUPP') or
00123                 why.errno != errno.EOPNOTSUPP):
00124                 raise

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.copytree (   src,
  dst,
  symlinks = False,
  ignore = None,
  copy_function = copy2,
  ignore_dangling_symlinks = False 
)
Recursively copy a directory tree.

The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.

If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the contents of the files pointed to by symbolic
links are copied. If the file pointed by the symlink doesn't
exist, an exception will be added in the list of errors raised in
an Error exception at the end of the copy process.

You can set the optional ignore_dangling_symlinks flag to true if you
want to silence this exception. Notice that this has no effect on
platforms that don't support os.symlink.

The optional ignore argument is a callable. If given, it
is called with the `src` parameter, which is the directory
being visited by copytree(), and `names` which is the list of
`src` contents, as returned by os.listdir():

    callable(src, names) -> ignored_names

Since copytree() is called recursively, the callable will be
called once for each directory that is copied. It returns a
list of names relative to the `src` directory that should
not be copied.

The optional copy_function argument is a callable that will be used
to copy each file. It will be called with the source path and the
destination path as arguments. By default, copy2() is used, but any
function that supports the same signature (like copy()) can be used.

Definition at line 160 of file shutil.py.

00160 
00161              ignore_dangling_symlinks=False):
00162     """Recursively copy a directory tree.
00163 
00164     The destination directory must not already exist.
00165     If exception(s) occur, an Error is raised with a list of reasons.
00166 
00167     If the optional symlinks flag is true, symbolic links in the
00168     source tree result in symbolic links in the destination tree; if
00169     it is false, the contents of the files pointed to by symbolic
00170     links are copied. If the file pointed by the symlink doesn't
00171     exist, an exception will be added in the list of errors raised in
00172     an Error exception at the end of the copy process.
00173 
00174     You can set the optional ignore_dangling_symlinks flag to true if you
00175     want to silence this exception. Notice that this has no effect on
00176     platforms that don't support os.symlink.
00177 
00178     The optional ignore argument is a callable. If given, it
00179     is called with the `src` parameter, which is the directory
00180     being visited by copytree(), and `names` which is the list of
00181     `src` contents, as returned by os.listdir():
00182 
00183         callable(src, names) -> ignored_names
00184 
00185     Since copytree() is called recursively, the callable will be
00186     called once for each directory that is copied. It returns a
00187     list of names relative to the `src` directory that should
00188     not be copied.
00189 
00190     The optional copy_function argument is a callable that will be used
00191     to copy each file. It will be called with the source path and the
00192     destination path as arguments. By default, copy2() is used, but any
00193     function that supports the same signature (like copy()) can be used.
00194 
00195     """
00196     names = os.listdir(src)
00197     if ignore is not None:
00198         ignored_names = ignore(src, names)
00199     else:
00200         ignored_names = set()
00201 
00202     os.makedirs(dst)
00203     errors = []
00204     for name in names:
00205         if name in ignored_names:
00206             continue
00207         srcname = os.path.join(src, name)
00208         dstname = os.path.join(dst, name)
00209         try:
00210             if os.path.islink(srcname):
00211                 linkto = os.readlink(srcname)
00212                 if symlinks:
00213                     os.symlink(linkto, dstname)
00214                 else:
00215                     # ignore dangling symlink if the flag is on
00216                     if not os.path.exists(linkto) and ignore_dangling_symlinks:
00217                         continue
00218                     # otherwise let the copy occurs. copy2 will raise an error
00219                     copy_function(srcname, dstname)
00220             elif os.path.isdir(srcname):
00221                 copytree(srcname, dstname, symlinks, ignore, copy_function)
00222             else:
00223                 # Will raise a SpecialFileError for unsupported file types
00224                 copy_function(srcname, dstname)
00225         # catch the Error from the recursive copytree so that we can
00226         # continue with other files
00227         except Error as err:
00228             errors.extend(err.args[0])
00229         except EnvironmentError as why:
00230             errors.append((srcname, dstname, str(why)))
00231     try:
00232         copystat(src, dst)
00233     except OSError as why:
00234         if WindowsError is not None and isinstance(why, WindowsError):
00235             # Copying file access times may fail on Windows
00236             pass
00237         else:
00238             errors.extend((src, dst, str(why)))
00239     if errors:
00240         raise Error(errors)

Here is the call graph for this function:

Here is the caller graph for this function:

Returns a list of supported formats for archiving and unarchiving.

Each element of the returned sequence is a tuple (name, description)

Definition at line 505 of file shutil.py.

00505 
00506 def get_archive_formats():
00507     """Returns a list of supported formats for archiving and unarchiving.
00508 
00509     Each element of the returned sequence is a tuple (name, description)
00510     """
00511     formats = [(name, registry[2]) for name, registry in
00512                _ARCHIVE_FORMATS.items()]
00513     formats.sort()
00514     return formats

Here is the caller graph for this function:

Returns a list of supported formats for unpacking.

Each element of the returned sequence is a tuple
(name, extensions, description)

Definition at line 594 of file shutil.py.

00594 
00595 def get_unpack_formats():
00596     """Returns a list of supported formats for unpacking.
00597 
00598     Each element of the returned sequence is a tuple
00599     (name, extensions, description)
00600     """
00601     formats = [(name, info[0], info[3]) for name, info in
00602                _UNPACK_FORMATS.items()]
00603     formats.sort()
00604     return formats

Here is the caller graph for this function:

def shutil.ignore_patterns (   patterns)
Function that can be used as copytree() ignore parameter.

Patterns is a sequence of glob-style patterns
that are used to exclude files

Definition at line 147 of file shutil.py.

00147 
00148 def ignore_patterns(*patterns):
00149     """Function that can be used as copytree() ignore parameter.
00150 
00151     Patterns is a sequence of glob-style patterns
00152     that are used to exclude files"""
00153     def _ignore_patterns(path, names):
00154         ignored_names = []
00155         for pattern in patterns:
00156             ignored_names.extend(fnmatch.filter(names, pattern))
00157         return set(ignored_names)
00158     return _ignore_patterns

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.make_archive (   base_name,
  format,
  root_dir = None,
  base_dir = None,
  verbose = 0,
  dry_run = 0,
  owner = None,
  group = None,
  logger = None 
)
Create an archive file (eg. zip or tar).

'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "tar", "bztar"
or "gztar".

'root_dir' is a directory that will be the root directory of the
archive; ie. we typically chdir into 'root_dir' before creating the
archive.  'base_dir' is the directory where we start archiving from;
ie. 'base_dir' will be the common prefix of all files and
directories in the archive.  'root_dir' and 'base_dir' both default
to the current directory.  Returns the name of the archive file.

'owner' and 'group' are used when creating a tar archive. By default,
uses the current owner and group.

Definition at line 540 of file shutil.py.

00540 
00541                  dry_run=0, owner=None, group=None, logger=None):
00542     """Create an archive file (eg. zip or tar).
00543 
00544     'base_name' is the name of the file to create, minus any format-specific
00545     extension; 'format' is the archive format: one of "zip", "tar", "bztar"
00546     or "gztar".
00547 
00548     'root_dir' is a directory that will be the root directory of the
00549     archive; ie. we typically chdir into 'root_dir' before creating the
00550     archive.  'base_dir' is the directory where we start archiving from;
00551     ie. 'base_dir' will be the common prefix of all files and
00552     directories in the archive.  'root_dir' and 'base_dir' both default
00553     to the current directory.  Returns the name of the archive file.
00554 
00555     'owner' and 'group' are used when creating a tar archive. By default,
00556     uses the current owner and group.
00557     """
00558     save_cwd = os.getcwd()
00559     if root_dir is not None:
00560         if logger is not None:
00561             logger.debug("changing into '%s'", root_dir)
00562         base_name = os.path.abspath(base_name)
00563         if not dry_run:
00564             os.chdir(root_dir)
00565 
00566     if base_dir is None:
00567         base_dir = os.curdir
00568 
00569     kwargs = {'dry_run': dry_run, 'logger': logger}
00570 
00571     try:
00572         format_info = _ARCHIVE_FORMATS[format]
00573     except KeyError:
00574         raise ValueError("unknown archive format '%s'" % format)
00575 
00576     func = format_info[0]
00577     for arg, val in format_info[1]:
00578         kwargs[arg] = val
00579 
00580     if format != 'zip':
00581         kwargs['owner'] = owner
00582         kwargs['group'] = group
00583 
00584     try:
00585         filename = func(base_name, base_dir, **kwargs)
00586     finally:
00587         if root_dir is not None:
00588             if logger is not None:
00589                 logger.debug("changing back to '%s'", save_cwd)
00590             os.chdir(save_cwd)
00591 
00592     return filename
00593 

Here is the caller graph for this function:

def shutil.move (   src,
  dst 
)
Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.

If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.

If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.

If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here...  A look at a mv.c shows a lot of
the issues this implementation glosses over.

Definition at line 295 of file shutil.py.

00295 
00296 def move(src, dst):
00297     """Recursively move a file or directory to another location. This is
00298     similar to the Unix "mv" command.
00299 
00300     If the destination is a directory or a symlink to a directory, the source
00301     is moved inside the directory. The destination path must not already
00302     exist.
00303 
00304     If the destination already exists but is not a directory, it may be
00305     overwritten depending on os.rename() semantics.
00306 
00307     If the destination is on our current filesystem, then rename() is used.
00308     Otherwise, src is copied to the destination and then removed.
00309     A lot more could be done here...  A look at a mv.c shows a lot of
00310     the issues this implementation glosses over.
00311 
00312     """
00313     real_dst = dst
00314     if os.path.isdir(dst):
00315         if _samefile(src, dst):
00316             # We might be on a case insensitive filesystem,
00317             # perform the rename anyway.
00318             os.rename(src, dst)
00319             return
00320 
00321         real_dst = os.path.join(dst, _basename(src))
00322         if os.path.exists(real_dst):
00323             raise Error("Destination path '%s' already exists" % real_dst)
00324     try:
00325         os.rename(src, real_dst)
00326     except OSError as exc:
00327         if os.path.isdir(src):
00328             if _destinsrc(src, dst):
00329                 raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
00330             copytree(src, real_dst, symlinks=True)
00331             rmtree(src)
00332         else:
00333             copy2(src, real_dst)
00334             os.unlink(src)

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.register_archive_format (   name,
  function,
  extra_args = None,
  description = '' 
)
Registers an archive format.

name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.

Definition at line 515 of file shutil.py.

00515 
00516 def register_archive_format(name, function, extra_args=None, description=''):
00517     """Registers an archive format.
00518 
00519     name is the name of the format. function is the callable that will be
00520     used to create archives. If provided, extra_args is a sequence of
00521     (name, value) tuples that will be passed as arguments to the callable.
00522     description can be provided to describe the format, and will be returned
00523     by the get_archive_formats() function.
00524     """
00525     if extra_args is None:
00526         extra_args = []
00527     if not isinstance(function, collections.Callable):
00528         raise TypeError('The %s object is not callable' % function)
00529     if not isinstance(extra_args, (tuple, list)):
00530         raise TypeError('extra_args needs to be a sequence')
00531     for element in extra_args:
00532         if not isinstance(element, (tuple, list)) or len(element) !=2 :
00533             raise TypeError('extra_args elements are : (arg_name, value)')
00534 
00535     _ARCHIVE_FORMATS[name] = (function, extra_args, description)

Here is the caller graph for this function:

def shutil.register_unpack_format (   name,
  extensions,
  function,
  extra_args = None,
  description = '' 
)
Registers an unpack format.

`name` is the name of the format. `extensions` is a list of extensions
corresponding to the format.

`function` is the callable that will be
used to unpack archives. The callable will receive archives to unpack.
If it's unable to handle an archive, it needs to raise a ReadError
exception.

If provided, `extra_args` is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_unpack_formats() function.

Definition at line 624 of file shutil.py.

00624 
00625                            description=''):
00626     """Registers an unpack format.
00627 
00628     `name` is the name of the format. `extensions` is a list of extensions
00629     corresponding to the format.
00630 
00631     `function` is the callable that will be
00632     used to unpack archives. The callable will receive archives to unpack.
00633     If it's unable to handle an archive, it needs to raise a ReadError
00634     exception.
00635 
00636     If provided, `extra_args` is a sequence of
00637     (name, value) tuples that will be passed as arguments to the callable.
00638     description can be provided to describe the format, and will be returned
00639     by the get_unpack_formats() function.
00640     """
00641     if extra_args is None:
00642         extra_args = []
00643     _check_unpack_options(extensions, function, extra_args)
00644     _UNPACK_FORMATS[name] = extensions, function, extra_args, description

Here is the call graph for this function:

Here is the caller graph for this function:

def shutil.rmtree (   path,
  ignore_errors = False,
  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 with arguments (func,
path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
path is the argument to that function that caused it to fail; and
exc_info is a tuple returned by sys.exc_info().  If ignore_errors
is false and onerror is None, an exception is raised.

Definition at line 241 of file shutil.py.

00241 
00242 def rmtree(path, ignore_errors=False, onerror=None):
00243     """Recursively delete a directory tree.
00244 
00245     If ignore_errors is set, errors are ignored; otherwise, if onerror
00246     is set, it is called to handle the error with arguments (func,
00247     path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
00248     path is the argument to that function that caused it to fail; and
00249     exc_info is a tuple returned by sys.exc_info().  If ignore_errors
00250     is false and onerror is None, an exception is raised.
00251 
00252     """
00253     if ignore_errors:
00254         def onerror(*args):
00255             pass
00256     elif onerror is None:
00257         def onerror(*args):
00258             raise
00259     try:
00260         if os.path.islink(path):
00261             # symlinks to directories are forbidden, see bug #1669
00262             raise OSError("Cannot call rmtree on a symbolic link")
00263     except OSError:
00264         onerror(os.path.islink, path, sys.exc_info())
00265         # can't continue even if onerror hook returns
00266         return
00267     names = []
00268     try:
00269         names = os.listdir(path)
00270     except os.error as err:
00271         onerror(os.listdir, path, sys.exc_info())
00272     for name in names:
00273         fullname = os.path.join(path, name)
00274         try:
00275             mode = os.lstat(fullname).st_mode
00276         except os.error:
00277             mode = 0
00278         if stat.S_ISDIR(mode):
00279             rmtree(fullname, ignore_errors, onerror)
00280         else:
00281             try:
00282                 os.remove(fullname)
00283             except os.error as err:
00284                 onerror(os.remove, fullname, sys.exc_info())
00285     try:
00286         os.rmdir(path)
00287     except os.error:
00288         onerror(os.rmdir, path, sys.exc_info())
00289 

def shutil.unpack_archive (   filename,
  extract_dir = None,
  format = None 
)
Unpack an archive.

`filename` is the name of the archive.

`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.

`format` is the archive format: one of "zip", "tar", or "gztar". Or any
other registered format. If not provided, unpack_archive will use the
filename extension and see if an unpacker was registered for that
extension.

In case none is found, a ValueError is raised.

Definition at line 722 of file shutil.py.

00722 
00723 def unpack_archive(filename, extract_dir=None, format=None):
00724     """Unpack an archive.
00725 
00726     `filename` is the name of the archive.
00727 
00728     `extract_dir` is the name of the target directory, where the archive
00729     is unpacked. If not provided, the current working directory is used.
00730 
00731     `format` is the archive format: one of "zip", "tar", or "gztar". Or any
00732     other registered format. If not provided, unpack_archive will use the
00733     filename extension and see if an unpacker was registered for that
00734     extension.
00735 
00736     In case none is found, a ValueError is raised.
00737     """
00738     if extract_dir is None:
00739         extract_dir = os.getcwd()
00740 
00741     if format is not None:
00742         try:
00743             format_info = _UNPACK_FORMATS[format]
00744         except KeyError:
00745             raise ValueError("Unknown unpack format '{0}'".format(format))
00746 
00747         func = format_info[1]
00748         func(filename, extract_dir, **dict(format_info[2]))
00749     else:
00750         # we need to look at the registered unpackers supported extensions
00751         format = _find_unpack_format(filename)
00752         if format is None:
00753             raise ReadError("Unknown archive format '{0}'".format(filename))
00754 
00755         func = _UNPACK_FORMATS[format][1]
00756         kwargs = dict(_UNPACK_FORMATS[format][2])
00757         func(filename, extract_dir, **kwargs)

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 536 of file shutil.py.

00536 
00537 def unregister_archive_format(name):
00538     del _ARCHIVE_FORMATS[name]

Here is the call graph for this function:

Here is the caller graph for this function:

Removes the pack format from the registery.

Definition at line 645 of file shutil.py.

00645 
00646 def unregister_unpack_format(name):
00647     """Removes the pack format from the registery."""
00648     del _UNPACK_FORMATS[name]

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
00002            "copytree", "move", "rmtree", "Error", "SpecialFileError",
00003            "ExecError", "make_archive", "get_archive_formats",
00004            "register_archive_format", "unregister_archive_format",
00005            "get_unpack_formats", "register_unpack_format",
00006            "unregister_unpack_format", "unpack_archive", "ignore_patterns"]

Definition at line 32 of file shutil.py.

Initial value:
00001 {
00002     'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
00003     'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
00004     'tar':   (_make_tarball, [('compress', None)], "uncompressed tar file"),
00005     'zip':   (_make_zipfile, [],"ZIP file")
00006     }

Definition at line 494 of file shutil.py.

Definition at line 18 of file shutil.py.

Initial value:
00001 {
00002     'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"),
00003     'tar':   (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
00004     'zip':   (['.zip'], _unpack_zipfile, [], "ZIP file")
00005     }

Definition at line 705 of file shutil.py.

Definition at line 30 of file shutil.py.

Definition at line 25 of file shutil.py.

Definition at line 60 of file shutil.py.