desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Seek to a position in the file.'
| def seek(self, pos, whence=os.SEEK_SET):
| if self.closed:
raise ValueError('I/O operation on closed file')
if (whence == os.SEEK_SET):
self.position = min(max(pos, 0), self.size)
elif (whence == os.SEEK_CUR):
if (pos < 0):
self.position = max((self.position + pos), 0)
else:
self.position = min((self.position + pos), self.size)
elif (whence == os.SEEK_END):
self.position = max(min((self.size + pos), self.size), 0)
else:
raise ValueError('Invalid argument')
self.buffer = ''
self.fileobj.seek(self.position)
|
'Close the file object.'
| def close(self):
| self.closed = True
|
'Get an iterator over the file\'s lines.'
| def __iter__(self):
| while True:
line = self.readline()
if (not line):
break
(yield line)
|
'Construct a TarInfo object. name is the optional name
of the member.'
| def __init__(self, name=''):
| self.name = name
self.mode = 420
self.uid = 0
self.gid = 0
self.size = 0
self.mtime = 0
self.chksum = 0
self.type = REGTYPE
self.linkname = ''
self.uname = ''
self.gname = ''
self.devmajor = 0
self.devminor = 0
self.offset = 0
self.offset_data = 0
self.pax_headers = {}
|
'Return the TarInfo\'s attributes as a dictionary.'
| def get_info(self, encoding, errors):
| info = {'name': self.name, 'mode': (self.mode & 4095), 'uid': self.uid, 'gid': self.gid, 'size': self.size, 'mtime': self.mtime, 'chksum': self.chksum, 'type': self.type, 'linkname': self.linkname, 'uname': self.uname, 'gname': self.gname, 'devmajor': self.devmajor, 'devminor': self.devminor}
if ((info['type'] == DIRTYPE) and (not info['name'].endswith('/'))):
info['name'] += '/'
for key in ('name', 'linkname', 'uname', 'gname'):
if (type(info[key]) is unicode):
info[key] = info[key].encode(encoding, errors)
return info
|
'Return a tar header as a string of 512 byte blocks.'
| def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict'):
| info = self.get_info(encoding, errors)
if (format == USTAR_FORMAT):
return self.create_ustar_header(info)
elif (format == GNU_FORMAT):
return self.create_gnu_header(info)
elif (format == PAX_FORMAT):
return self.create_pax_header(info, encoding, errors)
else:
raise ValueError('invalid format')
|
'Return the object as a ustar header block.'
| def create_ustar_header(self, info):
| info['magic'] = POSIX_MAGIC
if (len(info['linkname']) > LENGTH_LINK):
raise ValueError('linkname is too long')
if (len(info['name']) > LENGTH_NAME):
(info['prefix'], info['name']) = self._posix_split_name(info['name'])
return self._create_header(info, USTAR_FORMAT)
|
'Return the object as a GNU header block sequence.'
| def create_gnu_header(self, info):
| info['magic'] = GNU_MAGIC
buf = ''
if (len(info['linkname']) > LENGTH_LINK):
buf += self._create_gnu_long_header(info['linkname'], GNUTYPE_LONGLINK)
if (len(info['name']) > LENGTH_NAME):
buf += self._create_gnu_long_header(info['name'], GNUTYPE_LONGNAME)
return (buf + self._create_header(info, GNU_FORMAT))
|
'Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information.'
| def create_pax_header(self, info, encoding, errors):
| info['magic'] = POSIX_MAGIC
pax_headers = self.pax_headers.copy()
for (name, hname, length) in (('name', 'path', LENGTH_NAME), ('linkname', 'linkpath', LENGTH_LINK), ('uname', 'uname', 32), ('gname', 'gname', 32)):
if (hname in pax_headers):
continue
val = info[name].decode(encoding, errors)
try:
val.encode('ascii')
except UnicodeEncodeError:
pax_headers[hname] = val
continue
if (len(info[name]) > length):
pax_headers[hname] = val
for (name, digits) in (('uid', 8), ('gid', 8), ('size', 12), ('mtime', 12)):
if (name in pax_headers):
info[name] = 0
continue
val = info[name]
if ((not (0 <= val < (8 ** (digits - 1)))) or isinstance(val, float)):
pax_headers[name] = unicode(val)
info[name] = 0
if pax_headers:
buf = self._create_pax_generic_header(pax_headers)
else:
buf = ''
return (buf + self._create_header(info, USTAR_FORMAT))
|
'Return the object as a pax global header block sequence.'
| @classmethod
def create_pax_global_header(cls, pax_headers):
| return cls._create_pax_generic_header(pax_headers, type=XGLTYPE)
|
'Split a name longer than 100 chars into a prefix
and a name part.'
| def _posix_split_name(self, name):
| prefix = name[:(LENGTH_PREFIX + 1)]
while (prefix and (prefix[(-1)] != '/')):
prefix = prefix[:(-1)]
name = name[len(prefix):]
prefix = prefix[:(-1)]
if ((not prefix) or (len(name) > LENGTH_NAME)):
raise ValueError('name is too long')
return (prefix, name)
|
'Return a header block. info is a dictionary with file
information, format must be one of the *_FORMAT constants.'
| @staticmethod
def _create_header(info, format):
| parts = [stn(info.get('name', ''), 100), itn((info.get('mode', 0) & 4095), 8, format), itn(info.get('uid', 0), 8, format), itn(info.get('gid', 0), 8, format), itn(info.get('size', 0), 12, format), itn(info.get('mtime', 0), 12, format), ' ', info.get('type', REGTYPE), stn(info.get('linkname', ''), 100), stn(info.get('magic', POSIX_MAGIC), 8), stn(info.get('uname', ''), 32), stn(info.get('gname', ''), 32), itn(info.get('devmajor', 0), 8, format), itn(info.get('devminor', 0), 8, format), stn(info.get('prefix', ''), 155)]
buf = struct.pack(('%ds' % BLOCKSIZE), ''.join(parts))
chksum = calc_chksums(buf[(- BLOCKSIZE):])[0]
buf = ((buf[:(-364)] + ('%06o\x00' % chksum)) + buf[(-357):])
return buf
|
'Return the string payload filled with zero bytes
up to the next 512 byte border.'
| @staticmethod
def _create_payload(payload):
| (blocks, remainder) = divmod(len(payload), BLOCKSIZE)
if (remainder > 0):
payload += ((BLOCKSIZE - remainder) * NUL)
return payload
|
'Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
for name.'
| @classmethod
def _create_gnu_long_header(cls, name, type):
| name += NUL
info = {}
info['name'] = '././@LongLink'
info['type'] = type
info['size'] = len(name)
info['magic'] = GNU_MAGIC
return (cls._create_header(info, USTAR_FORMAT) + cls._create_payload(name))
|
'Return a POSIX.1-2001 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be unicode objects.'
| @classmethod
def _create_pax_generic_header(cls, pax_headers, type=XHDTYPE):
| records = []
for (keyword, value) in pax_headers.iteritems():
keyword = keyword.encode('utf8')
value = value.encode('utf8')
l = ((len(keyword) + len(value)) + 3)
n = p = 0
while True:
n = (l + len(str(p)))
if (n == p):
break
p = n
records.append(('%d %s=%s\n' % (p, keyword, value)))
records = ''.join(records)
info = {}
info['name'] = '././@PaxHeader'
info['type'] = type
info['size'] = len(records)
info['magic'] = POSIX_MAGIC
return (cls._create_header(info, USTAR_FORMAT) + cls._create_payload(records))
|
'Construct a TarInfo object from a 512 byte string buffer.'
| @classmethod
def frombuf(cls, buf):
| if (len(buf) == 0):
raise EmptyHeaderError('empty header')
if (len(buf) != BLOCKSIZE):
raise TruncatedHeaderError('truncated header')
if (buf.count(NUL) == BLOCKSIZE):
raise EOFHeaderError('end of file header')
chksum = nti(buf[148:156])
if (chksum not in calc_chksums(buf)):
raise InvalidHeaderError('bad checksum')
obj = cls()
obj.buf = buf
obj.name = nts(buf[0:100])
obj.mode = nti(buf[100:108])
obj.uid = nti(buf[108:116])
obj.gid = nti(buf[116:124])
obj.size = nti(buf[124:136])
obj.mtime = nti(buf[136:148])
obj.chksum = chksum
obj.type = buf[156:157]
obj.linkname = nts(buf[157:257])
obj.uname = nts(buf[265:297])
obj.gname = nts(buf[297:329])
obj.devmajor = nti(buf[329:337])
obj.devminor = nti(buf[337:345])
prefix = nts(buf[345:500])
if ((obj.type == AREGTYPE) and obj.name.endswith('/')):
obj.type = DIRTYPE
if obj.isdir():
obj.name = obj.name.rstrip('/')
if (prefix and (obj.type not in GNU_TYPES)):
obj.name = ((prefix + '/') + obj.name)
return obj
|
'Return the next TarInfo object from TarFile object
tarfile.'
| @classmethod
def fromtarfile(cls, tarfile):
| buf = tarfile.fileobj.read(BLOCKSIZE)
obj = cls.frombuf(buf)
obj.offset = (tarfile.fileobj.tell() - BLOCKSIZE)
return obj._proc_member(tarfile)
|
'Choose the right processing method depending on
the type and call it.'
| def _proc_member(self, tarfile):
| if (self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK)):
return self._proc_gnulong(tarfile)
elif (self.type == GNUTYPE_SPARSE):
return self._proc_sparse(tarfile)
elif (self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE)):
return self._proc_pax(tarfile)
else:
return self._proc_builtin(tarfile)
|
'Process a builtin type or an unknown type which
will be treated as a regular file.'
| def _proc_builtin(self, tarfile):
| self.offset_data = tarfile.fileobj.tell()
offset = self.offset_data
if (self.isreg() or (self.type not in SUPPORTED_TYPES)):
offset += self._block(self.size)
tarfile.offset = offset
self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
return self
|
'Process the blocks that hold a GNU longname
or longlink member.'
| def _proc_gnulong(self, tarfile):
| buf = tarfile.fileobj.read(self._block(self.size))
try:
next = self.fromtarfile(tarfile)
except HeaderError:
raise SubsequentHeaderError('missing or bad subsequent header')
next.offset = self.offset
if (self.type == GNUTYPE_LONGNAME):
next.name = nts(buf)
elif (self.type == GNUTYPE_LONGLINK):
next.linkname = nts(buf)
return next
|
'Process a GNU sparse header plus extra headers.'
| def _proc_sparse(self, tarfile):
| buf = self.buf
sp = _ringbuffer()
pos = 386
lastpos = 0L
realpos = 0L
for i in xrange(4):
try:
offset = nti(buf[pos:(pos + 12)])
numbytes = nti(buf[(pos + 12):(pos + 24)])
except ValueError:
break
if (offset > lastpos):
sp.append(_hole(lastpos, (offset - lastpos)))
sp.append(_data(offset, numbytes, realpos))
realpos += numbytes
lastpos = (offset + numbytes)
pos += 24
isextended = ord(buf[482])
origsize = nti(buf[483:495])
while (isextended == 1):
buf = tarfile.fileobj.read(BLOCKSIZE)
pos = 0
for i in xrange(21):
try:
offset = nti(buf[pos:(pos + 12)])
numbytes = nti(buf[(pos + 12):(pos + 24)])
except ValueError:
break
if (offset > lastpos):
sp.append(_hole(lastpos, (offset - lastpos)))
sp.append(_data(offset, numbytes, realpos))
realpos += numbytes
lastpos = (offset + numbytes)
pos += 24
isextended = ord(buf[504])
if (lastpos < origsize):
sp.append(_hole(lastpos, (origsize - lastpos)))
self.sparse = sp
self.offset_data = tarfile.fileobj.tell()
tarfile.offset = (self.offset_data + self._block(self.size))
self.size = origsize
return self
|
'Process an extended or global header as described in
POSIX.1-2001.'
| def _proc_pax(self, tarfile):
| buf = tarfile.fileobj.read(self._block(self.size))
if (self.type == XGLTYPE):
pax_headers = tarfile.pax_headers
else:
pax_headers = tarfile.pax_headers.copy()
regex = re.compile('(\\d+) ([^=]+)=', re.U)
pos = 0
while True:
match = regex.match(buf, pos)
if (not match):
break
(length, keyword) = match.groups()
length = int(length)
value = buf[(match.end(2) + 1):((match.start(1) + length) - 1)]
keyword = keyword.decode('utf8')
value = value.decode('utf8')
pax_headers[keyword] = value
pos += length
try:
next = self.fromtarfile(tarfile)
except HeaderError:
raise SubsequentHeaderError('missing or bad subsequent header')
if (self.type in (XHDTYPE, SOLARIS_XHDTYPE)):
next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
next.offset = self.offset
if ('size' in pax_headers):
offset = next.offset_data
if (next.isreg() or (next.type not in SUPPORTED_TYPES)):
offset += next._block(next.size)
tarfile.offset = offset
return next
|
'Replace fields with supplemental information from a previous
pax extended or global header.'
| def _apply_pax_info(self, pax_headers, encoding, errors):
| for (keyword, value) in pax_headers.iteritems():
if (keyword not in PAX_FIELDS):
continue
if (keyword == 'path'):
value = value.rstrip('/')
if (keyword in PAX_NUMBER_FIELDS):
try:
value = PAX_NUMBER_FIELDS[keyword](value)
except ValueError:
value = 0
else:
value = uts(value, encoding, errors)
setattr(self, keyword, value)
self.pax_headers = pax_headers.copy()
|
'Round up a byte count by BLOCKSIZE and return it,
e.g. _block(834) => 1024.'
| def _block(self, count):
| (blocks, remainder) = divmod(count, BLOCKSIZE)
if remainder:
blocks += 1
return (blocks * BLOCKSIZE)
|
'Open an (uncompressed) tar archive `name\'. `mode\' is either \'r\' to
read from an existing archive, \'a\' to append data to an existing
file or \'w\' to create a new file overwriting an existing one. `mode\'
defaults to \'r\'.
If `fileobj\' is given, it is used for reading or writing data. If it
can be determined, `mode\' is overridden by `fileobj\'s mode.
`fileobj\' is not closed, when TarFile is closed.'
| def __init__(self, name=None, mode='r', fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, errors=None, pax_headers=None, debug=None, errorlevel=None):
| modes = {'r': 'rb', 'a': 'r+b', 'w': 'wb'}
if (mode not in modes):
raise ValueError("mode must be 'r', 'a' or 'w'")
self.mode = mode
self._mode = modes[mode]
if (not fileobj):
if ((self.mode == 'a') and (not os.path.exists(name))):
self.mode = 'w'
self._mode = 'wb'
fileobj = bltn_open(name, self._mode)
self._extfileobj = False
else:
if ((name is None) and hasattr(fileobj, 'name')):
name = fileobj.name
if hasattr(fileobj, 'mode'):
self._mode = fileobj.mode
self._extfileobj = True
self.name = (os.path.abspath(name) if name else None)
self.fileobj = fileobj
if (format is not None):
self.format = format
if (tarinfo is not None):
self.tarinfo = tarinfo
if (dereference is not None):
self.dereference = dereference
if (ignore_zeros is not None):
self.ignore_zeros = ignore_zeros
if (encoding is not None):
self.encoding = encoding
if (errors is not None):
self.errors = errors
elif (mode == 'r'):
self.errors = 'utf-8'
else:
self.errors = 'strict'
if ((pax_headers is not None) and (self.format == PAX_FORMAT)):
self.pax_headers = pax_headers
else:
self.pax_headers = {}
if (debug is not None):
self.debug = debug
if (errorlevel is not None):
self.errorlevel = errorlevel
self.closed = False
self.members = []
self._loaded = False
self.offset = self.fileobj.tell()
self.inodes = {}
try:
if (self.mode == 'r'):
self.firstmember = None
self.firstmember = self.next()
if (self.mode == 'a'):
while True:
self.fileobj.seek(self.offset)
try:
tarinfo = self.tarinfo.fromtarfile(self)
self.members.append(tarinfo)
except EOFHeaderError:
self.fileobj.seek(self.offset)
break
except HeaderError as e:
raise ReadError(str(e))
if (self.mode in 'aw'):
self._loaded = True
if self.pax_headers:
buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
self.fileobj.write(buf)
self.offset += len(buf)
except:
if (not self._extfileobj):
self.fileobj.close()
self.closed = True
raise
|
'Open a tar archive for reading, writing or appending. Return
an appropriate TarFile class.
mode:
\'r\' or \'r:*\' open for reading with transparent compression
\'r:\' open for reading exclusively uncompressed
\'r:gz\' open for reading with gzip compression
\'r:bz2\' open for reading with bzip2 compression
\'a\' or \'a:\' open for appending, creating the file if necessary
\'w\' or \'w:\' open for writing without compression
\'w:gz\' open for writing with gzip compression
\'w:bz2\' open for writing with bzip2 compression
\'r|*\' open a stream of tar blocks with transparent compression
\'r|\' open an uncompressed stream of tar blocks for reading
\'r|gz\' open a gzip compressed stream of tar blocks
\'r|bz2\' open a bzip2 compressed stream of tar blocks
\'w|\' open an uncompressed stream for writing
\'w|gz\' open a gzip compressed stream for writing
\'w|bz2\' open a bzip2 compressed stream for writing'
| @classmethod
def open(cls, name=None, mode='r', fileobj=None, bufsize=RECORDSIZE, **kwargs):
| if ((not name) and (not fileobj)):
raise ValueError('nothing to open')
if (mode in ('r', 'r:*')):
for comptype in cls.OPEN_METH:
func = getattr(cls, cls.OPEN_METH[comptype])
if (fileobj is not None):
saved_pos = fileobj.tell()
try:
return func(name, 'r', fileobj, **kwargs)
except (ReadError, CompressionError) as e:
if (fileobj is not None):
fileobj.seek(saved_pos)
continue
raise ReadError('file could not be opened successfully')
elif (':' in mode):
(filemode, comptype) = mode.split(':', 1)
filemode = (filemode or 'r')
comptype = (comptype or 'tar')
if (comptype in cls.OPEN_METH):
func = getattr(cls, cls.OPEN_METH[comptype])
else:
raise CompressionError(('unknown compression type %r' % comptype))
return func(name, filemode, fileobj, **kwargs)
elif ('|' in mode):
(filemode, comptype) = mode.split('|', 1)
filemode = (filemode or 'r')
comptype = (comptype or 'tar')
if (filemode not in ('r', 'w')):
raise ValueError("mode must be 'r' or 'w'")
stream = _Stream(name, filemode, comptype, fileobj, bufsize)
try:
t = cls(name, filemode, stream, **kwargs)
except:
stream.close()
raise
t._extfileobj = False
return t
elif (mode in ('a', 'w')):
return cls.taropen(name, mode, fileobj, **kwargs)
raise ValueError('undiscernible mode')
|
'Open uncompressed tar archive name for reading or writing.'
| @classmethod
def taropen(cls, name, mode='r', fileobj=None, **kwargs):
| if (mode not in ('r', 'a', 'w')):
raise ValueError("mode must be 'r', 'a' or 'w'")
return cls(name, mode, fileobj, **kwargs)
|
'Open gzip compressed tar archive name for reading or writing.
Appending is not allowed.'
| @classmethod
def gzopen(cls, name, mode='r', fileobj=None, compresslevel=9, **kwargs):
| if (mode not in ('r', 'w')):
raise ValueError("mode must be 'r' or 'w'")
try:
import gzip
gzip.GzipFile
except (ImportError, AttributeError):
raise CompressionError('gzip module is not available')
try:
fileobj = gzip.GzipFile(name, mode, compresslevel, fileobj)
except OSError:
if ((fileobj is not None) and (mode == 'r')):
raise ReadError('not a gzip file')
raise
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
except IOError:
fileobj.close()
if (mode == 'r'):
raise ReadError('not a gzip file')
raise
except:
fileobj.close()
raise
t._extfileobj = False
return t
|
'Open bzip2 compressed tar archive name for reading or writing.
Appending is not allowed.'
| @classmethod
def bz2open(cls, name, mode='r', fileobj=None, compresslevel=9, **kwargs):
| if (mode not in ('r', 'w')):
raise ValueError("mode must be 'r' or 'w'.")
try:
import bz2
except ImportError:
raise CompressionError('bz2 module is not available')
if (fileobj is not None):
fileobj = _BZ2Proxy(fileobj, mode)
else:
fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
except (IOError, EOFError):
fileobj.close()
if (mode == 'r'):
raise ReadError('not a bzip2 file')
raise
except:
fileobj.close()
raise
t._extfileobj = False
return t
|
'Close the TarFile. In write-mode, two finishing zero blocks are
appended to the archive.'
| def close(self):
| if self.closed:
return
self.closed = True
try:
if (self.mode in 'aw'):
self.fileobj.write((NUL * (BLOCKSIZE * 2)))
self.offset += (BLOCKSIZE * 2)
(blocks, remainder) = divmod(self.offset, RECORDSIZE)
if (remainder > 0):
self.fileobj.write((NUL * (RECORDSIZE - remainder)))
finally:
if (not self._extfileobj):
self.fileobj.close()
|
'Return a TarInfo object for member `name\'. If `name\' can not be
found in the archive, KeyError is raised. If a member occurs more
than once in the archive, its last occurrence is assumed to be the
most up-to-date version.'
| def getmember(self, name):
| tarinfo = self._getmember(name)
if (tarinfo is None):
raise KeyError(('filename %r not found' % name))
return tarinfo
|
'Return the members of the archive as a list of TarInfo objects. The
list has the same order as the members in the archive.'
| def getmembers(self):
| self._check()
if (not self._loaded):
self._load()
return self.members
|
'Return the members of the archive as a list of their names. It has
the same order as the list returned by getmembers().'
| def getnames(self):
| return [tarinfo.name for tarinfo in self.getmembers()]
|
'Create a TarInfo object from the result of os.stat or equivalent
on an existing file. The file is either named by `name\', or
specified as a file object `fileobj\' with a file descriptor. If
given, `arcname\' specifies an alternative name for the file in the
archive, otherwise, the name is taken from the \'name\' attribute of
\'fileobj\', or the \'name\' argument.'
| def gettarinfo(self, name=None, arcname=None, fileobj=None):
| self._check('aw')
if (fileobj is not None):
name = fileobj.name
if (arcname is None):
arcname = name
(drv, arcname) = os.path.splitdrive(arcname)
arcname = arcname.replace(os.sep, '/')
arcname = arcname.lstrip('/')
tarinfo = self.tarinfo()
tarinfo.tarfile = self
if (fileobj is None):
if (hasattr(os, 'lstat') and (not self.dereference)):
statres = os.lstat(name)
else:
statres = os.stat(name)
else:
statres = os.fstat(fileobj.fileno())
linkname = ''
stmd = statres.st_mode
if stat.S_ISREG(stmd):
inode = (statres.st_ino, statres.st_dev)
if ((not self.dereference) and (statres.st_nlink > 1) and (inode in self.inodes) and (arcname != self.inodes[inode])):
type = LNKTYPE
linkname = self.inodes[inode]
else:
type = REGTYPE
if inode[0]:
self.inodes[inode] = arcname
elif stat.S_ISDIR(stmd):
type = DIRTYPE
elif stat.S_ISFIFO(stmd):
type = FIFOTYPE
elif stat.S_ISLNK(stmd):
type = SYMTYPE
linkname = os.readlink(name)
elif stat.S_ISCHR(stmd):
type = CHRTYPE
elif stat.S_ISBLK(stmd):
type = BLKTYPE
else:
return None
tarinfo.name = arcname
tarinfo.mode = stmd
tarinfo.uid = statres.st_uid
tarinfo.gid = statres.st_gid
if (type == REGTYPE):
tarinfo.size = statres.st_size
else:
tarinfo.size = 0L
tarinfo.mtime = statres.st_mtime
tarinfo.type = type
tarinfo.linkname = linkname
if pwd:
try:
tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
except KeyError:
pass
if grp:
try:
tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
except KeyError:
pass
if (type in (CHRTYPE, BLKTYPE)):
if (hasattr(os, 'major') and hasattr(os, 'minor')):
tarinfo.devmajor = os.major(statres.st_rdev)
tarinfo.devminor = os.minor(statres.st_rdev)
return tarinfo
|
'Print a table of contents to sys.stdout. If `verbose\' is False, only
the names of the members are printed. If it is True, an `ls -l\'-like
output is produced.'
| def list(self, verbose=True):
| self._check()
for tarinfo in self:
if verbose:
print filemode(tarinfo.mode),
print ('%s/%s' % ((tarinfo.uname or tarinfo.uid), (tarinfo.gname or tarinfo.gid))),
if (tarinfo.ischr() or tarinfo.isblk()):
print ('%10s' % ('%d,%d' % (tarinfo.devmajor, tarinfo.devminor))),
else:
print ('%10d' % tarinfo.size),
print ('%d-%02d-%02d %02d:%02d:%02d' % time.localtime(tarinfo.mtime)[:6]),
print (tarinfo.name + ('/' if tarinfo.isdir() else '')),
if verbose:
if tarinfo.issym():
print '->', tarinfo.linkname,
if tarinfo.islnk():
print 'link to', tarinfo.linkname,
print
|
'Add the file `name\' to the archive. `name\' may be any type of file
(directory, fifo, symbolic link, etc.). If given, `arcname\'
specifies an alternative name for the file in the archive.
Directories are added recursively by default. This can be avoided by
setting `recursive\' to False. `exclude\' is a function that should
return True for each filename to be excluded. `filter\' is a function
that expects a TarInfo object argument and returns the changed
TarInfo object, if it returns None the TarInfo object will be
excluded from the archive.'
| def add(self, name, arcname=None, recursive=True, exclude=None, filter=None):
| self._check('aw')
if (arcname is None):
arcname = name
if (exclude is not None):
import warnings
warnings.warn('use the filter argument instead', DeprecationWarning, 2)
if exclude(name):
self._dbg(2, ('tarfile: Excluded %r' % name))
return
if ((self.name is not None) and (os.path.abspath(name) == self.name)):
self._dbg(2, ('tarfile: Skipped %r' % name))
return
self._dbg(1, name)
tarinfo = self.gettarinfo(name, arcname)
if (tarinfo is None):
self._dbg(1, ('tarfile: Unsupported type %r' % name))
return
if (filter is not None):
tarinfo = filter(tarinfo)
if (tarinfo is None):
self._dbg(2, ('tarfile: Excluded %r' % name))
return
if tarinfo.isreg():
with bltn_open(name, 'rb') as f:
self.addfile(tarinfo, f)
elif tarinfo.isdir():
self.addfile(tarinfo)
if recursive:
for f in os.listdir(name):
self.add(os.path.join(name, f), os.path.join(arcname, f), recursive, exclude, filter)
else:
self.addfile(tarinfo)
|
'Add the TarInfo object `tarinfo\' to the archive. If `fileobj\' is
given, tarinfo.size bytes are read from it and added to the archive.
You can create TarInfo objects directly, or by using gettarinfo().
On Windows platforms, `fileobj\' should always be opened with mode
\'rb\' to avoid irritation about the file size.'
| def addfile(self, tarinfo, fileobj=None):
| self._check('aw')
tarinfo = copy.copy(tarinfo)
buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
self.fileobj.write(buf)
self.offset += len(buf)
if (fileobj is not None):
copyfileobj(fileobj, self.fileobj, tarinfo.size)
(blocks, remainder) = divmod(tarinfo.size, BLOCKSIZE)
if (remainder > 0):
self.fileobj.write((NUL * (BLOCKSIZE - remainder)))
blocks += 1
self.offset += (blocks * BLOCKSIZE)
self.members.append(tarinfo)
|
'Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path\' specifies a different directory
to extract to. `members\' is optional and must be a subset of the
list returned by getmembers().'
| def extractall(self, path='.', members=None):
| directories = []
if (members is None):
members = self
for tarinfo in members:
if tarinfo.isdir():
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 448
self.extract(tarinfo, path)
directories.sort(key=operator.attrgetter('name'))
directories.reverse()
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError as e:
if (self.errorlevel > 1):
raise
else:
self._dbg(1, ('tarfile: %s' % e))
|
'Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member\' may be a filename or a TarInfo object. You can
specify a different directory using `path\'.'
| def extract(self, member, path=''):
| self._check('r')
if isinstance(member, basestring):
tarinfo = self.getmember(member)
else:
tarinfo = member
if tarinfo.islnk():
tarinfo._link_target = os.path.join(path, tarinfo.linkname)
try:
self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
except EnvironmentError as e:
if (self.errorlevel > 0):
raise
elif (e.filename is None):
self._dbg(1, ('tarfile: %s' % e.strerror))
else:
self._dbg(1, ('tarfile: %s %r' % (e.strerror, e.filename)))
except ExtractError as e:
if (self.errorlevel > 1):
raise
else:
self._dbg(1, ('tarfile: %s' % e))
|
'Extract a member from the archive as a file object. `member\' may be
a filename or a TarInfo object. If `member\' is a regular file, a
file-like object is returned. If `member\' is a link, a file-like
object is constructed from the link\'s target. If `member\' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()'
| def extractfile(self, member):
| self._check('r')
if isinstance(member, basestring):
tarinfo = self.getmember(member)
else:
tarinfo = member
if tarinfo.isreg():
return self.fileobject(self, tarinfo)
elif (tarinfo.type not in SUPPORTED_TYPES):
return self.fileobject(self, tarinfo)
elif (tarinfo.islnk() or tarinfo.issym()):
if isinstance(self.fileobj, _Stream):
raise StreamError('cannot extract (sym)link as file object')
else:
return self.extractfile(self._find_link_target(tarinfo))
else:
return None
|
'Extract the TarInfo object tarinfo to a physical
file called targetpath.'
| def _extract_member(self, tarinfo, targetpath):
| targetpath = targetpath.rstrip('/')
targetpath = targetpath.replace('/', os.sep)
upperdirs = os.path.dirname(targetpath)
if (upperdirs and (not os.path.exists(upperdirs))):
os.makedirs(upperdirs)
if (tarinfo.islnk() or tarinfo.issym()):
self._dbg(1, ('%s -> %s' % (tarinfo.name, tarinfo.linkname)))
else:
self._dbg(1, tarinfo.name)
if tarinfo.isreg():
self.makefile(tarinfo, targetpath)
elif tarinfo.isdir():
self.makedir(tarinfo, targetpath)
elif tarinfo.isfifo():
self.makefifo(tarinfo, targetpath)
elif (tarinfo.ischr() or tarinfo.isblk()):
self.makedev(tarinfo, targetpath)
elif (tarinfo.islnk() or tarinfo.issym()):
self.makelink(tarinfo, targetpath)
elif (tarinfo.type not in SUPPORTED_TYPES):
self.makeunknown(tarinfo, targetpath)
else:
self.makefile(tarinfo, targetpath)
self.chown(tarinfo, targetpath)
if (not tarinfo.issym()):
self.chmod(tarinfo, targetpath)
self.utime(tarinfo, targetpath)
|
'Make a directory called targetpath.'
| def makedir(self, tarinfo, targetpath):
| try:
os.mkdir(targetpath, 448)
except EnvironmentError as e:
if (e.errno != errno.EEXIST):
raise
|
'Make a file called targetpath.'
| def makefile(self, tarinfo, targetpath):
| source = self.extractfile(tarinfo)
try:
with bltn_open(targetpath, 'wb') as target:
copyfileobj(source, target)
finally:
source.close()
|
'Make a file from a TarInfo object with an unknown type
at targetpath.'
| def makeunknown(self, tarinfo, targetpath):
| self.makefile(tarinfo, targetpath)
self._dbg(1, ('tarfile: Unknown file type %r, extracted as regular file.' % tarinfo.type))
|
'Make a fifo called targetpath.'
| def makefifo(self, tarinfo, targetpath):
| if hasattr(os, 'mkfifo'):
os.mkfifo(targetpath)
else:
raise ExtractError('fifo not supported by system')
|
'Make a character or block device called targetpath.'
| def makedev(self, tarinfo, targetpath):
| if ((not hasattr(os, 'mknod')) or (not hasattr(os, 'makedev'))):
raise ExtractError('special devices not supported by system')
mode = tarinfo.mode
if tarinfo.isblk():
mode |= stat.S_IFBLK
else:
mode |= stat.S_IFCHR
os.mknod(targetpath, mode, os.makedev(tarinfo.devmajor, tarinfo.devminor))
|
'Make a (symbolic) link called targetpath. If it cannot be created
(platform limitation), we try to make a copy of the referenced file
instead of a link.'
| def makelink(self, tarinfo, targetpath):
| if (hasattr(os, 'symlink') and hasattr(os, 'link')):
if tarinfo.issym():
if os.path.lexists(targetpath):
os.unlink(targetpath)
os.symlink(tarinfo.linkname, targetpath)
elif os.path.exists(tarinfo._link_target):
if os.path.lexists(targetpath):
os.unlink(targetpath)
os.link(tarinfo._link_target, targetpath)
else:
self._extract_member(self._find_link_target(tarinfo), targetpath)
else:
try:
self._extract_member(self._find_link_target(tarinfo), targetpath)
except KeyError:
raise ExtractError('unable to resolve link inside archive')
|
'Set owner of targetpath according to tarinfo.'
| def chown(self, tarinfo, targetpath):
| if (pwd and hasattr(os, 'geteuid') and (os.geteuid() == 0)):
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
u = tarinfo.uid
try:
if (tarinfo.issym() and hasattr(os, 'lchown')):
os.lchown(targetpath, u, g)
elif (sys.platform != 'os2emx'):
os.chown(targetpath, u, g)
except EnvironmentError as e:
raise ExtractError('could not change owner')
|
'Set file permissions of targetpath according to tarinfo.'
| def chmod(self, tarinfo, targetpath):
| if hasattr(os, 'chmod'):
try:
os.chmod(targetpath, tarinfo.mode)
except EnvironmentError as e:
raise ExtractError('could not change mode')
|
'Set modification time of targetpath according to tarinfo.'
| def utime(self, tarinfo, targetpath):
| if (not hasattr(os, 'utime')):
return
try:
os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
except EnvironmentError as e:
raise ExtractError('could not change modification time')
|
'Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.'
| def next(self):
| self._check('ra')
if (self.firstmember is not None):
m = self.firstmember
self.firstmember = None
return m
if (self.offset != self.fileobj.tell()):
self.fileobj.seek((self.offset - 1))
if (not self.fileobj.read(1)):
raise ReadError('unexpected end of data')
tarinfo = None
while True:
try:
tarinfo = self.tarinfo.fromtarfile(self)
except EOFHeaderError as e:
if self.ignore_zeros:
self._dbg(2, ('0x%X: %s' % (self.offset, e)))
self.offset += BLOCKSIZE
continue
except InvalidHeaderError as e:
if self.ignore_zeros:
self._dbg(2, ('0x%X: %s' % (self.offset, e)))
self.offset += BLOCKSIZE
continue
elif (self.offset == 0):
raise ReadError(str(e))
except EmptyHeaderError:
if (self.offset == 0):
raise ReadError('empty file')
except TruncatedHeaderError as e:
if (self.offset == 0):
raise ReadError(str(e))
except SubsequentHeaderError as e:
raise ReadError(str(e))
break
if (tarinfo is not None):
self.members.append(tarinfo)
else:
self._loaded = True
return tarinfo
|
'Find an archive member by name from bottom to top.
If tarinfo is given, it is used as the starting point.'
| def _getmember(self, name, tarinfo=None, normalize=False):
| members = self.getmembers()
if (tarinfo is not None):
members = members[:members.index(tarinfo)]
if normalize:
name = os.path.normpath(name)
for member in reversed(members):
if normalize:
member_name = os.path.normpath(member.name)
else:
member_name = member.name
if (name == member_name):
return member
|
'Read through the entire archive file and look for readable
members.'
| def _load(self):
| while True:
tarinfo = self.next()
if (tarinfo is None):
break
self._loaded = True
|
'Check if TarFile is still open, and if the operation\'s mode
corresponds to TarFile\'s mode.'
| def _check(self, mode=None):
| if self.closed:
raise IOError(('%s is closed' % self.__class__.__name__))
if ((mode is not None) and (self.mode not in mode)):
raise IOError(('bad operation for mode %r' % self.mode))
|
'Find the target member of a symlink or hardlink member in the
archive.'
| def _find_link_target(self, tarinfo):
| if tarinfo.issym():
linkname = '/'.join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname)))
limit = None
else:
linkname = tarinfo.linkname
limit = tarinfo
member = self._getmember(linkname, tarinfo=limit, normalize=True)
if (member is None):
raise KeyError(('linkname %r not found' % linkname))
return member
|
'Provide an iterator object.'
| def __iter__(self):
| if self._loaded:
return iter(self.members)
else:
return TarIter(self)
|
'Write debugging output to sys.stderr.'
| def _dbg(self, level, msg):
| if (level <= self.debug):
print >>sys.stderr, msg
|
'Construct a TarIter object.'
| def __init__(self, tarfile):
| self.tarfile = tarfile
self.index = 0
|
'Return iterator object.'
| def __iter__(self):
| return self
|
'Return the next item using TarFile\'s next() method.
When all members have been read, set TarFile as _loaded.'
| def next(self):
| if ((self.index == 0) and (self.tarfile.firstmember is not None)):
tarinfo = self.tarfile.next()
elif (self.index < len(self.tarfile.members)):
tarinfo = self.tarfile.members[self.index]
elif (not self.tarfile._loaded):
tarinfo = self.tarfile.next()
if (not tarinfo):
self.tarfile._loaded = True
raise StopIteration
else:
raise StopIteration
self.index += 1
return tarinfo
|
'Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.'
| def task_done(self):
| self.all_tasks_done.acquire()
try:
unfinished = (self.unfinished_tasks - 1)
if (unfinished <= 0):
if (unfinished < 0):
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
|
'Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.'
| def join(self):
| self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
|
'Return the approximate size of the queue (not reliable!).'
| def qsize(self):
| self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
|
'Return True if the queue is empty, False otherwise (not reliable!).'
| def empty(self):
| self.mutex.acquire()
n = (not self._qsize())
self.mutex.release()
return n
|
'Return True if the queue is full, False otherwise (not reliable!).'
| def full(self):
| self.mutex.acquire()
n = (0 < self.maxsize == self._qsize())
self.mutex.release()
return n
|
'Put an item into the queue.
If optional args \'block\' is true and \'timeout\' is None (the default),
block if necessary until a free slot is available. If \'timeout\' is
a non-negative number, it blocks at most \'timeout\' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise (\'block\' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception (\'timeout\'
is ignored in that case).'
| def put(self, item, block=True, timeout=None):
| self.not_full.acquire()
try:
if (self.maxsize > 0):
if (not block):
if (self._qsize() == self.maxsize):
raise Full
elif (timeout is None):
while (self._qsize() == self.maxsize):
self.not_full.wait()
elif (timeout < 0):
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = (_time() + timeout)
while (self._qsize() == self.maxsize):
remaining = (endtime - _time())
if (remaining <= 0.0):
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
|
'Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.'
| def put_nowait(self, item):
| return self.put(item, False)
|
'Remove and return an item from the queue.
If optional args \'block\' is true and \'timeout\' is None (the default),
block if necessary until an item is available. If \'timeout\' is
a non-negative number, it blocks at most \'timeout\' seconds and raises
the Empty exception if no item was available within that time.
Otherwise (\'block\' is false), return an item if one is immediately
available, else raise the Empty exception (\'timeout\' is ignored
in that case).'
| def get(self, block=True, timeout=None):
| self.not_empty.acquire()
try:
if (not block):
if (not self._qsize()):
raise Empty
elif (timeout is None):
while (not self._qsize()):
self.not_empty.wait()
elif (timeout < 0):
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = (_time() + timeout)
while (not self._qsize()):
remaining = (endtime - _time())
if (remaining <= 0.0):
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
|
'Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.'
| def get_nowait(self):
| return self.get(False)
|
'Merge in the data from another CoverageResults'
| def update(self, other):
| counts = self.counts
calledfuncs = self.calledfuncs
callers = self.callers
other_counts = other.counts
other_calledfuncs = other.calledfuncs
other_callers = other.callers
for key in other_counts.keys():
counts[key] = (counts.get(key, 0) + other_counts[key])
for key in other_calledfuncs.keys():
calledfuncs[key] = 1
for key in other_callers.keys():
callers[key] = 1
|
'@param coverdir'
| def write_results(self, show_missing=True, summary=False, coverdir=None):
| if self.calledfuncs:
print
print 'functions called:'
calls = self.calledfuncs.keys()
calls.sort()
for (filename, modulename, funcname) in calls:
print ('filename: %s, modulename: %s, funcname: %s' % (filename, modulename, funcname))
if self.callers:
print
print 'calling relationships:'
calls = self.callers.keys()
calls.sort()
lastfile = lastcfile = ''
for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
if (pfile != lastfile):
print
print '***', pfile, '***'
lastfile = pfile
lastcfile = ''
if ((cfile != pfile) and (lastcfile != cfile)):
print ' -->', cfile
lastcfile = cfile
print (' %s.%s -> %s.%s' % (pmod, pfunc, cmod, cfunc))
per_file = {}
for (filename, lineno) in self.counts.keys():
lines_hit = per_file[filename] = per_file.get(filename, {})
lines_hit[lineno] = self.counts[(filename, lineno)]
sums = {}
for (filename, count) in per_file.iteritems():
if (filename == '<string>'):
continue
if filename.startswith('<doctest '):
continue
if filename.endswith(('.pyc', '.pyo')):
filename = filename[:(-1)]
if (coverdir is None):
dir = os.path.dirname(os.path.abspath(filename))
modulename = modname(filename)
else:
dir = coverdir
if (not os.path.exists(dir)):
os.makedirs(dir)
modulename = fullmodname(filename)
if show_missing:
lnotab = find_executable_linenos(filename)
else:
lnotab = {}
source = linecache.getlines(filename)
coverpath = os.path.join(dir, (modulename + '.cover'))
(n_hits, n_lines) = self.write_results_file(coverpath, source, lnotab, count)
if (summary and n_lines):
percent = ((100 * n_hits) // n_lines)
sums[modulename] = (n_lines, percent, modulename, filename)
if (summary and sums):
mods = sums.keys()
mods.sort()
print 'lines cov% module (path)'
for m in mods:
(n_lines, percent, modulename, filename) = sums[m]
print ('%5d %3d%% %s (%s)' % sums[m])
if self.outfile:
try:
pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1)
except IOError as err:
print >>sys.stderr, ("Can't save counts files because %s" % err)
|
'Return a coverage results file in path.'
| def write_results_file(self, path, lines, lnotab, lines_hit):
| try:
outfile = open(path, 'w')
except IOError as err:
print >>sys.stderr, ('trace: Could not open %r for writing: %s- skipping' % (path, err))
return (0, 0)
n_lines = 0
n_hits = 0
for (i, line) in enumerate(lines):
lineno = (i + 1)
if (lineno in lines_hit):
outfile.write(('%5d: ' % lines_hit[lineno]))
n_hits += 1
n_lines += 1
elif rx_blank.match(line):
outfile.write(' ')
elif ((lineno in lnotab) and (not (PRAGMA_NOCOVER in lines[i]))):
outfile.write('>>>>>> ')
n_lines += 1
else:
outfile.write(' ')
outfile.write(lines[i].expandtabs(8))
outfile.close()
return (n_hits, n_lines)
|
'@param count true iff it should count number of times each
line is executed
@param trace true iff it should print out each line that is
being counted
@param countfuncs true iff it should just output a list of
(filename, modulename, funcname,) for functions
that were called at least once; This overrides
`count\' and `trace\'
@param ignoremods a list of the names of modules to ignore
@param ignoredirs a list of the names of directories to ignore
all of the (recursive) contents of
@param infile file from which to read stored counts to be
added into the results
@param outfile file in which to write the results
@param timing true iff timing information be displayed'
| def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False):
| self.infile = infile
self.outfile = outfile
self.ignore = Ignore(ignoremods, ignoredirs)
self.counts = {}
self.blabbed = {}
self.pathtobasename = {}
self.donothing = 0
self.trace = trace
self._calledfuncs = {}
self._callers = {}
self._caller_cache = {}
self.start_time = None
if timing:
self.start_time = time.time()
if countcallers:
self.globaltrace = self.globaltrace_trackcallers
elif countfuncs:
self.globaltrace = self.globaltrace_countfuncs
elif (trace and count):
self.globaltrace = self.globaltrace_lt
self.localtrace = self.localtrace_trace_and_count
elif trace:
self.globaltrace = self.globaltrace_lt
self.localtrace = self.localtrace_trace
elif count:
self.globaltrace = self.globaltrace_lt
self.localtrace = self.localtrace_count
else:
self.donothing = 1
|
'Handler for call events.
Adds information about who called who to the self._callers dict.'
| def globaltrace_trackcallers(self, frame, why, arg):
| if (why == 'call'):
this_func = self.file_module_function_of(frame)
parent_func = self.file_module_function_of(frame.f_back)
self._callers[(parent_func, this_func)] = 1
|
'Handler for call events.
Adds (filename, modulename, funcname) to the self._calledfuncs dict.'
| def globaltrace_countfuncs(self, frame, why, arg):
| if (why == 'call'):
this_func = self.file_module_function_of(frame)
self._calledfuncs[this_func] = 1
|
'Handler for call events.
If the code block being entered is to be ignored, returns `None\',
else returns self.localtrace.'
| def globaltrace_lt(self, frame, why, arg):
| if (why == 'call'):
code = frame.f_code
filename = frame.f_globals.get('__file__', None)
if filename:
modulename = modname(filename)
if (modulename is not None):
ignore_it = self.ignore.names(filename, modulename)
if (not ignore_it):
if self.trace:
print (' --- modulename: %s, funcname: %s' % (modulename, code.co_name))
return self.localtrace
else:
return None
|
'The parameter \'cmd\' is the shell command to execute in a
sub-process. On UNIX, \'cmd\' may be a sequence, in which case arguments
will be passed directly to the program without shell intervention (as
with os.spawnv()). If \'cmd\' is a string it will be passed to the shell
(as with os.system()). The \'capturestderr\' flag, if true, specifies
that the object should capture standard error output of the child
process. The default is false. If the \'bufsize\' parameter is
specified, it specifies the size of the I/O buffers to/from the child
process.'
| def __init__(self, cmd, capturestderr=False, bufsize=(-1)):
| _cleanup()
self.cmd = cmd
(p2cread, p2cwrite) = os.pipe()
(c2pread, c2pwrite) = os.pipe()
if capturestderr:
(errout, errin) = os.pipe()
self.pid = os.fork()
if (self.pid == 0):
os.dup2(p2cread, 0)
os.dup2(c2pwrite, 1)
if capturestderr:
os.dup2(errin, 2)
self._run_child(cmd)
os.close(p2cread)
self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
os.close(c2pwrite)
self.fromchild = os.fdopen(c2pread, 'r', bufsize)
if capturestderr:
os.close(errin)
self.childerr = os.fdopen(errout, 'r', bufsize)
else:
self.childerr = None
|
'Return the exit status of the child process if it has finished,
or -1 if it hasn\'t finished yet.'
| def poll(self, _deadstate=None):
| if (self.sts < 0):
try:
(pid, sts) = os.waitpid(self.pid, os.WNOHANG)
if (pid == self.pid):
self.sts = sts
except os.error:
if (_deadstate is not None):
self.sts = _deadstate
return self.sts
|
'Wait for and return the exit status of the child process.'
| def wait(self):
| if (self.sts < 0):
(pid, sts) = os.waitpid(self.pid, 0)
assert (pid == self.pid)
self.sts = sts
return self.sts
|
'Returns an instance of the RExec class.
The hooks parameter is an instance of the RHooks class or a subclass
of it. If it is omitted or None, the default RHooks class is
instantiated.
Whenever the RExec module searches for a module (even a built-in one)
or reads a module\'s code, it doesn\'t actually go out to the file
system itself. Rather, it calls methods of an RHooks instance that
was passed to or created by its constructor. (Actually, the RExec
object doesn\'t make these calls --- they are made by a module loader
object that\'s part of the RExec object. This allows another level of
flexibility, which can be useful when changing the mechanics of
import within the restricted environment.)
By providing an alternate RHooks object, we can control the file
system accesses made to import a module, without changing the
actual algorithm that controls the order in which those accesses are
made. For instance, we could substitute an RHooks object that
passes all filesystem requests to a file server elsewhere, via some
RPC mechanism such as ILU. Grail\'s applet loader uses this to support
importing applets from a URL for a directory.
If the verbose parameter is true, additional debugging output may be
sent to standard output.'
| def __init__(self, hooks=None, verbose=0):
| raise RuntimeError, 'This code is not secure in Python 2.2 and later'
ihooks._Verbose.__init__(self, verbose)
self.hooks = (hooks or RHooks(verbose))
self.hooks.set_rexec(self)
self.modules = {}
self.ok_dynamic_modules = self.ok_builtin_modules
list = []
for mname in self.ok_builtin_modules:
if (mname in sys.builtin_module_names):
list.append(mname)
self.ok_builtin_modules = tuple(list)
self.set_trusted_path()
self.make_builtin()
self.make_initial_modules()
self.make_sys()
self.loader = RModuleLoader(self.hooks, verbose)
self.importer = RModuleImporter(self.loader, verbose)
|
'Execute code within a restricted environment.
The code parameter must either be a string containing one or more
lines of Python code, or a compiled code object, which will be
executed in the restricted environment\'s __main__ module.'
| def r_exec(self, code):
| m = self.add_module('__main__')
exec code in m.__dict__
|
'Evaluate code within a restricted environment.
The code parameter must either be a string containing a Python
expression, or a compiled code object, which will be evaluated in
the restricted environment\'s __main__ module. The value of the
expression or code object will be returned.'
| def r_eval(self, code):
| m = self.add_module('__main__')
return eval(code, m.__dict__)
|
'Execute the Python code in the file in the restricted
environment\'s __main__ module.'
| def r_execfile(self, file):
| m = self.add_module('__main__')
execfile(file, m.__dict__)
|
'Import a module, raising an ImportError exception if the module
is considered unsafe.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.'
| def r_import(self, mname, globals={}, locals={}, fromlist=[]):
| return self.importer.import_module(mname, globals, locals, fromlist)
|
'Reload the module object, re-parsing and re-initializing it.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.'
| def r_reload(self, m):
| return self.importer.reload(m)
|
'Unload the module.
Removes it from the restricted environment\'s sys.modules dictionary.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.'
| def r_unload(self, m):
| return self.importer.unload(m)
|
'Execute code within a restricted environment.
Similar to the r_exec() method, but the code will be granted access
to restricted versions of the standard I/O streams sys.stdin,
sys.stderr, and sys.stdout.
The code parameter must either be a string containing one or more
lines of Python code, or a compiled code object, which will be
executed in the restricted environment\'s __main__ module.'
| def s_exec(self, *args):
| return self.s_apply(self.r_exec, args)
|
'Evaluate code within a restricted environment.
Similar to the r_eval() method, but the code will be granted access
to restricted versions of the standard I/O streams sys.stdin,
sys.stderr, and sys.stdout.
The code parameter must either be a string containing a Python
expression, or a compiled code object, which will be evaluated in
the restricted environment\'s __main__ module. The value of the
expression or code object will be returned.'
| def s_eval(self, *args):
| return self.s_apply(self.r_eval, args)
|
'Execute the Python code in the file in the restricted
environment\'s __main__ module.
Similar to the r_execfile() method, but the code will be granted
access to restricted versions of the standard I/O streams sys.stdin,
sys.stderr, and sys.stdout.'
| def s_execfile(self, *args):
| return self.s_apply(self.r_execfile, args)
|
'Import a module, raising an ImportError exception if the module
is considered unsafe.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.
Similar to the r_import() method, but has access to restricted
versions of the standard I/O streams sys.stdin, sys.stderr, and
sys.stdout.'
| def s_import(self, *args):
| return self.s_apply(self.r_import, args)
|
'Reload the module object, re-parsing and re-initializing it.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.
Similar to the r_reload() method, but has access to restricted
versions of the standard I/O streams sys.stdin, sys.stderr, and
sys.stdout.'
| def s_reload(self, *args):
| return self.s_apply(self.r_reload, args)
|
'Unload the module.
Removes it from the restricted environment\'s sys.modules dictionary.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.
Similar to the r_unload() method, but has access to restricted
versions of the standard I/O streams sys.stdin, sys.stderr, and
sys.stdout.'
| def s_unload(self, *args):
| return self.s_apply(self.r_unload, args)
|
'Method called when open() is called in the restricted environment.
The arguments are identical to those of the open() function, and a
file object (or a class instance compatible with file objects)
should be returned. RExec\'s default behaviour is allow opening
any file for reading, but forbidding any attempt to write a file.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.'
| def r_open(self, file, mode='r', buf=(-1)):
| mode = str(mode)
if (mode not in ('r', 'rb')):
raise IOError, "can't open files for writing in restricted mode"
return open(file, mode, buf)
|
'Connect to host. Arguments are:
- host: hostname to connect to (string, default previous host)
- port: port to connect to (integer, default previous port)'
| def connect(self, host='', port=0, timeout=(-999)):
| if (host != ''):
self.host = host
if (port > 0):
self.port = port
if (timeout != (-999)):
self.timeout = timeout
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
return self.welcome
|
'Get the welcome message from the server.
(this is read and squirreled away by connect())'
| def getwelcome(self):
| if self.debugging:
print '*welcome*', self.sanitize(self.welcome)
return self.welcome
|
'Set the debugging level.
The required argument level means:
0: no debugging output (default)
1: print commands and responses but not body text etc.
2: also print raw lines read and sent before stripping CR/LF'
| def set_debuglevel(self, level):
| self.debugging = level
|
'Use passive or active mode for data transfers.
With a false argument, use the normal PORT mode,
With a true argument, use the PASV command.'
| def set_pasv(self, val):
| self.passiveserver = val
|
'Expect a response beginning with \'2\'.'
| def voidresp(self):
| resp = self.getresp()
if (resp[:1] != '2'):
raise error_reply, resp
return resp
|
'Abort a file transfer. Uses out-of-band data.
This does not follow the procedure from the RFC to send Telnet
IP and Synch; that doesn\'t seem to work with the servers I\'ve
tried. Instead, just send the ABOR command as OOB data.'
| def abort(self):
| line = ('ABOR' + CRLF)
if (self.debugging > 1):
print '*put urgent*', self.sanitize(line)
self.sock.sendall(line, MSG_OOB)
resp = self.getmultiline()
if (resp[:3] not in ('426', '225', '226')):
raise error_proto, resp
|
'Send a command and return the response.'
| def sendcmd(self, cmd):
| self.putcmd(cmd)
return self.getresp()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.