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.po...
'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...
'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'] ...
'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 Va...
'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_he...
'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(encod...
'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('lin...
'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 ...
'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_...
'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...
'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...
'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.a...
'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 ...
'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...
'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, `...
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' ...
'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 compr...
@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: ...
'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,...
'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: fi...
'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.fil...
'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\' attr...
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 (f...
'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, tari...
'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 ...
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)) r...
'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, BLOCKS...
'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('...
'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 ...
'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 obje...
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.is...
'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,...
'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....
'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): ...
'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 (...
'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...
'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_nam...
'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 Key...
'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): ...
'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 ta...
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 = unfini...
'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 ...
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...
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() ...
'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. Oth...
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 ...
'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_calle...
'@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.c...
'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 (...
'@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 `...
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 = N...
'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): ...
'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 \'capturestde...
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(erri...
'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 fi...
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 mn...
'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, ...
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 b...
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 ac...
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 versio...
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...
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...
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 = s...
'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()