desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Resolve a ``fragment`` within the referenced ``document``. :argument document: the referrant document :argument str fragment: a URI fragment to resolve within it'
def resolve_fragment(self, document, fragment):
fragment = fragment.lstrip(u'/') parts = (unquote(fragment).split(u'/') if fragment else []) for part in parts: part = part.replace(u'~1', u'/').replace(u'~0', u'~') if isinstance(document, Sequence): try: part = int(part) except ValueError: pass try: document = document[part] except (TypeError, LookupError): raise RefResolutionError(('Unresolvable JSON pointer: %r' % fragment)) return document
'Resolve a remote ``uri``. Does not check the store first, but stores the retrieved document in the store if :attr:`RefResolver.cache_remote` is True. .. note:: If the requests_ library is present, ``jsonschema`` will use it to request the remote ``uri``, so that the correct encoding is detected and used. If it isn\'t, or if the scheme of the ``uri`` is not ``http`` or ``https``, UTF-8 is assumed. :argument str uri: the URI to resolve :returns: the retrieved document .. _requests: http://pypi.python.org/pypi/requests/'
def resolve_remote(self, uri):
scheme = urlsplit(uri).scheme if (scheme in self.handlers): result = self.handlers[scheme](uri) elif ((scheme in [u'http', u'https']) and requests and (getattr(requests.Response, 'json', None) is not None)): if callable(requests.Response.json): result = requests.get(uri).json() else: result = requests.get(uri).json else: result = json.loads(urlopen(uri).read().decode('utf-8')) if self.cache_remote: self.store[uri] = result return result
'Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)'
def is_package(self, fullname):
return hasattr(self.__get_module(fullname), '__path__')
'Return None Required, if is_package is implemented'
def get_code(self, fullname):
self.__get_module(fullname) return None
'lazily compute value for name or raise AttributeError if unknown.'
def __makeattr(self, name):
target = None if ('__onfirstaccess__' in self.__map__): target = self.__map__.pop('__onfirstaccess__') importobj(*target)() try: (modpath, attrname) = self.__map__[name] except KeyError: if ((target is not None) and (name != '__onfirstaccess__')): return getattr(self, name) raise AttributeError(name) else: result = importobj(modpath, attrname) setattr(self, name, result) try: del self.__map__[name] except KeyError: pass return result
'call a function and raise an errno-exception if applicable.'
def checked_call(self, func, *args, **kwargs):
__tracebackhide__ = True try: return func(*args, **kwargs) except self.Error: raise except (OSError, EnvironmentError): (cls, value, tb) = sys.exc_info() if (not hasattr(value, 'errno')): raise __tracebackhide__ = False errno = value.errno try: if (not isinstance(value, WindowsError)): raise NameError except NameError: cls = self._geterrnoclass(errno) else: try: cls = self._geterrnoclass(_winerrnomap[errno]) except KeyError: raise value raise cls(('%s%r' % (func.__name__, args))) __tracebackhide__ = True
'write a message to the appropriate consumer(s)'
def __call__(self, *args):
func = self._keywordmapper.getconsumer(self._keywords) if (func is not None): func(self.Message(self._keywords, args))
'return a consumer matching the given keywords. tries to find the most suitable consumer by walking, starting from the back, the list of keywords, the first consumer matching a keyword is returned (falling back to py.log.default)'
def getconsumer(self, keywords):
for i in range(len(keywords), 0, (-1)): try: return self.keywords2consumer[keywords[:i]] except KeyError: continue return self.keywords2consumer.get('default', default_consumer)
'set a consumer for a set of keywords.'
def setconsumer(self, keywords, consumer):
if isinstance(keywords, str): keywords = tuple(filter(None, keywords.split())) elif hasattr(keywords, '_keywords'): keywords = keywords._keywords elif (not isinstance(keywords, tuple)): raise TypeError(('key %r is not a string or tuple' % (keywords,))) if ((consumer is not None) and (not py.builtin.callable(consumer))): if (not hasattr(consumer, 'write')): raise TypeError(('%r should be None, callable or file-like' % (consumer,))) consumer = File(consumer) self.keywords2consumer[keywords] = consumer
'write a message to the log'
def __call__(self, msg):
self._file.write((str(msg) + '\n')) if hasattr(self._file, 'flush'): self._file.flush()
'write a message to the log'
def __call__(self, msg):
if (not hasattr(self, '_file')): self._openfile() self._file.write((str(msg) + '\n')) if (not self._buffering): self._file.flush()
'write a message to the log'
def __call__(self, msg):
py.std.syslog.syslog(self.priority, str(msg))
'return a path object pointing to source code (note that it might not point to an actually existing file).'
@property def path(self):
p = py.path.local(self.raw.co_filename) if (not p.check()): p = self.raw.co_filename return p
'return a py.code.Source object for the full source file of the code'
@property def fullsource(self):
from py._code import source (full, _) = source.findsource(self.raw) return full
'return a py.code.Source object for the code object\'s source only'
def source(self):
return py.code.Source(self.raw)
'return a tuple with the argument names for the code object if \'var\' is set True also return the names of the variable and keyword arguments when present'
def getargs(self, var=False):
raw = self.raw argcount = raw.co_argcount if var: argcount += (raw.co_flags & CO_VARARGS) argcount += (raw.co_flags & CO_VARKEYWORDS) return raw.co_varnames[:argcount]
'statement this frame is at'
@property def statement(self):
if (self.code.fullsource is None): return py.code.Source('') return self.code.fullsource.getstatement(self.lineno)
'evaluate \'code\' in the frame \'vars\' are optional additional local variables returns the result of the evaluation'
def eval(self, code, **vars):
f_locals = self.f_locals.copy() f_locals.update(vars) return eval(code, self.f_globals, f_locals)
'exec \'code\' in the frame \'vars\' are optiona; additional local variables'
def exec_(self, code, **vars):
f_locals = self.f_locals.copy() f_locals.update(vars) py.builtin.exec_(code, self.f_globals, f_locals)
'return a \'safe\' (non-recursive, one-line) string repr for \'object\''
def repr(self, object):
return py.io.saferepr(object)
'return a list of tuples (name, value) for all arguments if \'var\' is set True also include the variable and keyword arguments when present'
def getargs(self, var=False):
retval = [] for arg in self.code.getargs(var): try: retval.append((arg, self.f_locals[arg])) except KeyError: pass return retval
'py.code.Source object for the current statement'
@property def statement(self):
source = self.frame.code.fullsource return source.getstatement(self.lineno)
'path to the source code'
@property def path(self):
return self.frame.code.path
'Reinterpret the failing statement and returns a detailed information about what operations are performed.'
def reinterpret(self):
if (self.exprinfo is None): source = str(self.statement).strip() x = py.code._reinterpret(source, self.frame, should_fail=True) if (not isinstance(x, str)): raise TypeError(('interpret returned non-string %r' % (x,))) self.exprinfo = x return self.exprinfo
'return failing source code.'
def getsource(self, astcache=None):
from py._code.source import getstatementrange_ast source = self.frame.code.fullsource if (source is None): return None key = astnode = None if (astcache is not None): key = self.frame.code.path if (key is not None): astnode = astcache.get(key, None) start = self.getfirstlinesource() try: (astnode, _, end) = getstatementrange_ast(self.lineno, source, astnode=astnode) except SyntaxError: end = (self.lineno + 1) else: if (key is not None): astcache[key] = astnode return source[start:end]
'return True if the current frame has a var __tracebackhide__ resolving to True mostly for internal use'
def ishidden(self):
try: return self.frame.f_locals['__tracebackhide__'] except KeyError: try: return self.frame.f_globals['__tracebackhide__'] except KeyError: return False
'initialize from given python traceback object.'
def __init__(self, tb):
if hasattr(tb, 'tb_next'): def f(cur): while (cur is not None): (yield self.Entry(cur)) cur = cur.tb_next list.__init__(self, f(tb)) else: list.__init__(self, tb)
'return a Traceback instance wrapping part of this Traceback by provding any combination of path, lineno and firstlineno, the first frame to start the to-be-returned traceback is determined this allows cutting the first part of a Traceback instance e.g. for formatting reasons (removing some uninteresting bits that deal with handling of the exception/traceback)'
def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
for x in self: code = x.frame.code codepath = code.path if (((path is None) or (codepath == path)) and ((excludepath is None) or (not hasattr(codepath, 'relto')) or (not codepath.relto(excludepath))) and ((lineno is None) or (x.lineno == lineno)) and ((firstlineno is None) or (x.frame.code.firstlineno == firstlineno))): return Traceback(x._rawentry) return self
'return a Traceback instance with certain items removed fn is a function that gets a single argument, a TracebackItem instance, and should return True when the item should be added to the Traceback, False when not by default this removes all the TracebackItems which are hidden (see ishidden() above)'
def filter(self, fn=(lambda x: (not x.ishidden()))):
return Traceback(filter(fn, self))
'return last non-hidden traceback entry that lead to the exception of a traceback.'
def getcrashentry(self):
for i in range((-1), ((- len(self)) - 1), (-1)): entry = self[i] if (not entry.ishidden()): return entry return self[(-1)]
'return the index of the frame/TracebackItem where recursion originates if appropriate, None if no recursion occurred'
def recursionindex(self):
cache = {} for (i, entry) in enumerate(self): key = (entry.frame.code.path, id(entry.frame.code.raw), entry.lineno) l = cache.setdefault(key, []) if l: f = entry.frame loc = f.f_locals for otherloc in l: if f.is_true(f.eval(co_equal, __recursioncache_locals_1=loc, __recursioncache_locals_2=otherloc)): return i l.append(entry.frame.f_locals) return None
'return the exception as a string when \'tryshort\' resolves to True, and the exception is a py.code._AssertionError, only the actual exception part of the exception representation is returned (so \'AssertionError: \' is removed from the beginning)'
def exconly(self, tryshort=False):
lines = format_exception_only(self.type, self.value) text = ''.join(lines) text = text.rstrip() if tryshort: if text.startswith(self._striptext): text = text[len(self._striptext):] return text
'return True if the exception is an instance of exc'
def errisinstance(self, exc):
return isinstance(self.value, exc)
'return str()able representation of this exception info. showlocals: show locals per traceback entry style: long|short|no|native traceback style tbfilter: hide entries (where __tracebackhide__ is true) in case of style==native, tbfilter and showlocals is ignored.'
def getrepr(self, showlocals=False, style='long', abspath=False, tbfilter=True, funcargs=False):
if (style == 'native'): return ReprExceptionInfo(ReprTracebackNative(py.std.traceback.format_exception(self.type, self.value, self.traceback[0]._rawentry)), self._getreprcrash()) fmt = FormattedExcinfo(showlocals=showlocals, style=style, abspath=abspath, tbfilter=tbfilter, funcargs=funcargs) return fmt.repr_excinfo(self)
'return formatted and marked up source lines.'
def get_source(self, source, line_index=(-1), excinfo=None, short=False):
lines = [] if ((source is None) or (line_index >= len(source.lines))): source = py.code.Source('???') line_index = 0 if (line_index < 0): line_index += len(source) space_prefix = ' ' if short: lines.append((space_prefix + source.lines[line_index].strip())) else: for line in source.lines[:line_index]: lines.append((space_prefix + line)) lines.append(((self.flow_marker + ' ') + source.lines[line_index])) for line in source.lines[(line_index + 1):]: lines.append((space_prefix + line)) if (excinfo is not None): indent = (4 if short else self._getindent(source)) lines.extend(self.get_exconly(excinfo, indent=indent, markall=True)) return lines
'return new source object with trailing and leading blank lines removed.'
def strip(self):
(start, end) = (0, len(self)) while ((start < end) and (not self.lines[start].strip())): start += 1 while ((end > start) and (not self.lines[(end - 1)].strip())): end -= 1 source = Source() source.lines[:] = self.lines[start:end] return source
'return a copy of the source object with \'before\' and \'after\' wrapped around it.'
def putaround(self, before='', after='', indent=(' ' * 4)):
before = Source(before) after = Source(after) newsource = Source() lines = [(indent + line) for line in self.lines] newsource.lines = ((before.lines + lines) + after.lines) return newsource
'return a copy of the source object with all lines indented by the given indent-string.'
def indent(self, indent=(' ' * 4)):
newsource = Source() newsource.lines = [(indent + line) for line in self.lines] return newsource
'return Source statement which contains the given linenumber (counted from 0).'
def getstatement(self, lineno, assertion=False):
(start, end) = self.getstatementrange(lineno, assertion) return self[start:end]
'return (start, end) tuple which spans the minimal statement region which containing the given lineno.'
def getstatementrange(self, lineno, assertion=False):
if (not (0 <= lineno < len(self))): raise IndexError('lineno out of range') (ast, start, end) = getstatementrange_ast(lineno, self) return (start, end)
'return a new source object deindented by offset. If offset is None then guess an indentation offset from the first non-blank line. Subsequent lines which have a lower indentation offset will be copied verbatim as they are assumed to be part of multilines.'
def deindent(self, offset=None):
newsource = Source() newsource.lines[:] = deindent(self.lines, offset) return newsource
'return True if source is parseable, heuristically deindenting it by default.'
def isparseable(self, deindent=True):
try: import parser except ImportError: syntax_checker = (lambda x: compile(x, 'asd', 'exec')) else: syntax_checker = parser.suite if deindent: source = str(self.deindent()) else: source = str(self) try: syntax_checker((source + '\n')) except KeyboardInterrupt: raise except Exception: return False else: return True
'return compiled code object. if filename is None invent an artificial filename which displays the source/line position of the caller frame.'
def compile(self, filename=None, mode='exec', flag=generators.compiler_flag, dont_inherit=0, _genframe=None):
if ((not filename) or py.path.local(filename).check(file=0)): if (_genframe is None): _genframe = sys._getframe(1) (fn, lineno) = (_genframe.f_code.co_filename, _genframe.f_lineno) base = ('<%d-codegen ' % self._compilecounter) self.__class__._compilecounter += 1 if (not filename): filename = (base + ('%s:%d>' % (fn, lineno))) else: filename = (base + ('%r %s:%d>' % (filename, fn, lineno))) source = ('\n'.join(self.lines) + '\n') try: co = cpy_compile(source, filename, mode, flag) except SyntaxError: ex = sys.exc_info()[1] msglines = self.lines[:ex.lineno] if ex.offset: msglines.append(((' ' * ex.offset) + '^')) msglines.append(('(code was compiled probably from here: %s)' % filename)) newex = SyntaxError('\n'.join(msglines)) newex.offset = ex.offset newex.lineno = ex.lineno newex.text = ex.text raise newex else: if (flag & _AST_FLAG): return co lines = [(x + '\n') for x in self.lines] py.std.linecache.cache[filename] = (1, None, lines, filename) return co
'save targetfd descriptor, and open a new temporary file there. If no tmpfile is specified a tempfile.Tempfile() will be opened in text mode.'
def __init__(self, targetfd, tmpfile=None, now=True, patchsys=False):
self.targetfd = targetfd if ((tmpfile is None) and (targetfd != 0)): f = tempfile.TemporaryFile('wb+') tmpfile = dupfile(f, encoding='UTF-8') f.close() self.tmpfile = tmpfile self._savefd = os.dup(self.targetfd) if patchsys: self._oldsys = getattr(sys, patchsysdict[targetfd]) if now: self.start()
'unpatch and clean up, returns the self.tmpfile (file object)'
def done(self):
os.dup2(self._savefd, self.targetfd) os.close(self._savefd) if (self.targetfd != 0): self.tmpfile.seek(0) if hasattr(self, '_oldsys'): setattr(sys, patchsysdict[self.targetfd], self._oldsys) return self.tmpfile
'write a string to the original file descriptor'
def writeorg(self, data):
tempfp = tempfile.TemporaryFile() try: os.dup2(self._savefd, tempfp.fileno()) tempfp.write(data) finally: tempfp.close()
'return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution.'
def call(cls, func, *args, **kwargs):
so = cls() try: res = func(*args, **kwargs) finally: (out, err) = so.reset() return (res, out, err)
'reset sys.stdout/stderr and return captured output as strings.'
def reset(self):
if hasattr(self, '_reset'): raise ValueError('was already reset') self._reset = True (outfile, errfile) = self.done(save=False) (out, err) = ('', '') if (outfile and (not outfile.closed)): out = outfile.read() outfile.close() if (errfile and (errfile != outfile) and (not errfile.closed)): err = errfile.read() errfile.close() return (out, err)
'return current snapshot captures, memorize tempfiles.'
def suspend(self):
outerr = self.readouterr() (outfile, errfile) = self.done() return outerr
'resume capturing with original temp files.'
def resume(self):
self.startall()
'return (outfile, errfile) and stop capturing.'
def done(self, save=True):
outfile = errfile = None if (hasattr(self, 'out') and (not self.out.tmpfile.closed)): outfile = self.out.done() if (hasattr(self, 'err') and (not self.err.tmpfile.closed)): errfile = self.err.done() if hasattr(self, 'in_'): tmpfile = self.in_.done() if save: self._save() return (outfile, errfile)
'return snapshot value of stdout/stderr capturings.'
def readouterr(self):
if hasattr(self, 'out'): out = self._readsnapshot(self.out.tmpfile) else: out = '' if hasattr(self, 'err'): err = self._readsnapshot(self.err.tmpfile) else: err = '' return [out, err]
'return (outfile, errfile) and stop capturing.'
def done(self, save=True):
outfile = errfile = None if (self.out and (not self.out.closed)): sys.stdout = self._oldout outfile = self.out outfile.seek(0) if (self.err and (not self.err.closed)): sys.stderr = self._olderr errfile = self.err errfile.seek(0) if self.in_: sys.stdin = self._oldin return (outfile, errfile)
'resume capturing with original temp files.'
def resume(self):
self.startall()
'return snapshot value of stdout/stderr capturings.'
def readouterr(self):
out = err = '' if self.out: out = self.out.getvalue() self.out.truncate(0) self.out.seek(0) if self.err: err = self.err.getvalue() self.err.truncate(0) self.err.seek(0) return (out, err)
'return group name of file.'
@property def group(self):
if iswin32: raise NotImplementedError('XXX win32') import grp entry = py.error.checked_call(grp.getgrgid, self.gid) return entry[0]
'change ownership to the given user and group. user and group may be specified by a number or by a name. if rec is True change ownership recursively.'
def chown(self, user, group, rec=0):
uid = getuserid(user) gid = getgroupid(group) if rec: for x in self.visit(rec=(lambda x: x.check(link=0))): if x.check(link=0): py.error.checked_call(os.chown, str(x), uid, gid) py.error.checked_call(os.chown, str(self), uid, gid)
'return value of a symbolic link.'
def readlink(self):
return py.error.checked_call(os.readlink, self.strpath)
'posix style hard link to another name.'
def mklinkto(self, oldname):
py.error.checked_call(os.link, str(oldname), str(self))
'create a symbolic link with the given value (pointing to another name).'
def mksymlinkto(self, value, absolute=1):
if absolute: py.error.checked_call(os.symlink, str(value), self.strpath) else: base = self.common(value) relsource = self.__class__(value).relto(base) reldest = self.relto(base) n = reldest.count(self.sep) target = self.sep.join(((('..',) * n) + (relsource,))) py.error.checked_call(os.symlink, target, self.strpath)
'Initialize and return a local Path instance. Path can be relative to the current directory. If path is None it defaults to the current working directory. If expanduser is True, tilde-expansion is performed. Note that Path instances always carry an absolute path. Note also that passing in a local path object will simply return the exact same path object. Use new() to get a new copy.'
def __init__(self, path=None, expanduser=False):
if (path is None): self.strpath = py.error.checked_call(os.getcwd) else: try: path = fspath(path) except TypeError: raise ValueError('can only pass None, Path instances or non-empty strings to LocalPath') if expanduser: path = os.path.expanduser(path) self.strpath = abspath(path)
'return True if \'other\' references the same file as \'self\'.'
def samefile(self, other):
other = fspath(other) if (not isabs(other)): other = abspath(other) if (self == other): return True if iswin32: return False return py.error.checked_call(os.path.samefile, self.strpath, other)
'remove a file or directory (or a directory tree if rec=1). if ignore_errors is True, errors while removing directories will be ignored.'
def remove(self, rec=1, ignore_errors=False):
if self.check(dir=1, link=0): if rec: if iswin32: self.chmod(448, rec=1) py.error.checked_call(py.std.shutil.rmtree, self.strpath, ignore_errors=ignore_errors) else: py.error.checked_call(os.rmdir, self.strpath) else: if iswin32: self.chmod(448) py.error.checked_call(os.remove, self.strpath)
'return hexdigest of hashvalue for this file.'
def computehash(self, hashtype='md5', chunksize=524288):
try: try: import hashlib as mod except ImportError: if (hashtype == 'sha1'): hashtype = 'sha' mod = __import__(hashtype) hash = getattr(mod, hashtype)() except (AttributeError, ImportError): raise ValueError(("Don't know how to compute %r hash" % (hashtype,))) f = self.open('rb') try: while 1: buf = f.read(chunksize) if (not buf): return hash.hexdigest() hash.update(buf) finally: f.close()
'create a modified version of this path. the following keyword arguments modify various path parts:: a:/some/path/to/a/file.ext xx drive xxxxxxxxxxxxxxxxx dirname xxxxxxxx basename xxxx purebasename xxx ext'
def new(self, **kw):
obj = object.__new__(self.__class__) if (not kw): obj.strpath = self.strpath return obj (drive, dirname, basename, purebasename, ext) = self._getbyspec('drive,dirname,basename,purebasename,ext') if ('basename' in kw): if (('purebasename' in kw) or ('ext' in kw)): raise ValueError(('invalid specification %r' % kw)) else: pb = kw.setdefault('purebasename', purebasename) try: ext = kw['ext'] except KeyError: pass else: if (ext and (not ext.startswith('.'))): ext = ('.' + ext) kw['basename'] = (pb + ext) if (('dirname' in kw) and (not kw['dirname'])): kw['dirname'] = drive else: kw.setdefault('dirname', dirname) kw.setdefault('sep', self.sep) obj.strpath = normpath(('%(dirname)s%(sep)s%(basename)s' % kw)) return obj
'see new for what \'spec\' can be.'
def _getbyspec(self, spec):
res = [] parts = self.strpath.split(self.sep) args = filter(None, spec.split(',')) append = res.append for name in args: if (name == 'drive'): append(parts[0]) elif (name == 'dirname'): append(self.sep.join(parts[:(-1)])) else: basename = parts[(-1)] if (name == 'basename'): append(basename) else: i = basename.rfind('.') if (i == (-1)): (purebasename, ext) = (basename, '') else: (purebasename, ext) = (basename[:i], basename[i:]) if (name == 'purebasename'): append(purebasename) elif (name == 'ext'): append(ext) else: raise ValueError(('invalid part specification %r' % name)) return res
'return the directory path joined with any given path arguments.'
def dirpath(self, *args, **kwargs):
if (not kwargs): path = object.__new__(self.__class__) path.strpath = dirname(self.strpath) if args: path = path.join(*args) return path return super(LocalPath, self).dirpath(*args, **kwargs)
'return a new path by appending all \'args\' as path components. if abs=1 is used restart from root if any of the args is an absolute path.'
def join(self, *args, **kwargs):
sep = self.sep strargs = [fspath(arg) for arg in args] strpath = self.strpath if kwargs.get('abs'): newargs = [] for arg in reversed(strargs): if isabs(arg): strpath = arg strargs = newargs break newargs.insert(0, arg) for arg in strargs: arg = arg.strip(sep) if iswin32: arg = arg.strip('/') arg = arg.replace('/', sep) strpath = ((strpath + sep) + arg) obj = object.__new__(self.__class__) obj.strpath = normpath(strpath) return obj
'return an opened file with the given mode. If ensure is True, create parent directories if needed.'
def open(self, mode='r', ensure=False, encoding=None):
if ensure: self.dirpath().ensure(dir=1) if encoding: return py.error.checked_call(io.open, self.strpath, mode, encoding=encoding) return py.error.checked_call(open, self.strpath, mode)
'list directory contents, possibly filter by the given fil func and possibly sorted.'
def listdir(self, fil=None, sort=None):
if ((fil is None) and (sort is None)): names = py.error.checked_call(os.listdir, self.strpath) return map_as_list(self._fastjoin, names) if isinstance(fil, py.builtin._basestring): if (not self._patternchars.intersection(fil)): child = self._fastjoin(fil) if exists(child.strpath): return [child] return [] fil = common.FNMatcher(fil) names = py.error.checked_call(os.listdir, self.strpath) res = [] for name in names: child = self._fastjoin(name) if ((fil is None) or fil(child)): res.append(child) self._sortlist(res, sort) return res
'return size of the underlying file object'
def size(self):
return self.stat().size
'return last modification time of the path.'
def mtime(self):
return self.stat().mtime
'copy path to target. If mode is True, will copy copy permission from path to target. If stat is True, copy permission, last modification time, last access time, and flags from path to target.'
def copy(self, target, mode=False, stat=False):
if self.check(file=1): if target.check(dir=1): target = target.join(self.basename) assert (self != target) copychunked(self, target) if mode: copymode(self.strpath, target.strpath) if stat: copystat(self, target) else: def rec(p): return p.check(link=0) for x in self.visit(rec=rec): relpath = x.relto(self) newx = target.join(relpath) newx.dirpath().ensure(dir=1) if x.check(link=1): newx.mksymlinkto(x.readlink()) continue elif x.check(file=1): copychunked(x, newx) elif x.check(dir=1): newx.ensure(dir=1) if mode: copymode(x.strpath, newx.strpath) if stat: copystat(x, newx)
'rename this path to target.'
def rename(self, target):
target = fspath(target) return py.error.checked_call(os.rename, self.strpath, target)
'pickle object into path location'
def dump(self, obj, bin=1):
f = self.open('wb') try: py.error.checked_call(py.std.pickle.dump, obj, f, bin) finally: f.close()
'create & return the directory joined with args.'
def mkdir(self, *args):
p = self.join(*args) py.error.checked_call(os.mkdir, fspath(p)) return p
'write binary data into path. If ensure is True create missing parent directories.'
def write_binary(self, data, ensure=False):
if ensure: self.dirpath().ensure(dir=1) with self.open('wb') as f: f.write(data)
'write text data into path using the specified encoding. If ensure is True create missing parent directories.'
def write_text(self, data, encoding, ensure=False):
if ensure: self.dirpath().ensure(dir=1) with self.open('w', encoding=encoding) as f: f.write(data)
'write data into path. If ensure is True create missing parent directories.'
def write(self, data, mode='w', ensure=False):
if ensure: self.dirpath().ensure(dir=1) if ('b' in mode): if (not py.builtin._isbytes(data)): raise ValueError('can only process bytes') elif (not py.builtin._istext(data)): if (not py.builtin._isbytes(data)): data = str(data) else: data = py.builtin._totext(data, sys.getdefaultencoding()) f = self.open(mode) try: f.write(data) finally: f.close()
'ensure that an args-joined path exists (by default as a file). if you specify a keyword argument \'dir=True\' then the path is forced to be a directory path.'
def ensure(self, *args, **kwargs):
p = self.join(*args) if kwargs.get('dir', 0): return p._ensuredirs() else: p.dirpath()._ensuredirs() if (not p.check(file=1)): p.open('w').close() return p
'Return an os.stat() tuple.'
def stat(self, raising=True):
if (raising == True): return Stat(self, py.error.checked_call(os.stat, self.strpath)) try: return Stat(self, os.stat(self.strpath)) except KeyboardInterrupt: raise except Exception: return None
'Return an os.lstat() tuple.'
def lstat(self):
return Stat(self, py.error.checked_call(os.lstat, self.strpath))
'set modification time for the given path. if \'mtime\' is None (the default) then the file\'s mtime is set to current time. Note that the resolution for \'mtime\' is platform dependent.'
def setmtime(self, mtime=None):
if (mtime is None): return py.error.checked_call(os.utime, self.strpath, mtime) try: return py.error.checked_call(os.utime, self.strpath, ((-1), mtime)) except py.error.EINVAL: return py.error.checked_call(os.utime, self.strpath, (self.atime(), mtime))
'change directory to self and return old current directory'
def chdir(self):
try: old = self.__class__() except py.error.ENOENT: old = None py.error.checked_call(os.chdir, self.strpath) return old
'return context manager which changes to current dir during the managed "with" context. On __enter__ it returns the old dir.'
@contextmanager def as_cwd(self):
old = self.chdir() try: (yield old) finally: old.chdir()
'return a new path which contains no symbolic links.'
def realpath(self):
return self.__class__(os.path.realpath(self.strpath))
'return last access time of the path.'
def atime(self):
return self.stat().atime
'return string representation of the Path.'
def __str__(self):
return self.strpath
'change permissions to the given mode. If mode is an integer it directly encodes the os-specific modes. if rec is True perform recursively.'
def chmod(self, mode, rec=0):
if (not isinstance(mode, int)): raise TypeError(('mode %r must be an integer' % (mode,))) if rec: for x in self.visit(rec=rec): py.error.checked_call(os.chmod, str(x), mode) py.error.checked_call(os.chmod, self.strpath, mode)
'return the Python package path by looking for the last directory upwards which still contains an __init__.py. Return None if a pkgpath can not be determined.'
def pypkgpath(self):
pkgpath = None for parent in self.parts(reverse=True): if parent.isdir(): if (not parent.join('__init__.py').exists()): break if (not isimportable(parent.basename)): break pkgpath = parent return pkgpath
'return path as an imported python module. If modname is None, look for the containing package and construct an according module name. The module will be put/looked up in sys.modules. if ensuresyspath is True then the root dir for importing the file (taking __init__.py files into account) will be prepended to sys.path if it isn\'t there already. If ensuresyspath=="append" the root dir will be appended if it isn\'t already contained in sys.path. if ensuresyspath is False no modification of syspath happens.'
def pyimport(self, modname=None, ensuresyspath=True):
if (not self.check()): raise py.error.ENOENT(self) pkgpath = None if (modname is None): pkgpath = self.pypkgpath() if (pkgpath is not None): pkgroot = pkgpath.dirpath() names = self.new(ext='').relto(pkgroot).split(self.sep) if (names[(-1)] == '__init__'): names.pop() modname = '.'.join(names) else: pkgroot = self.dirpath() modname = self.purebasename self._ensuresyspath(ensuresyspath, pkgroot) __import__(modname) mod = sys.modules[modname] if (self.basename == '__init__.py'): return mod modfile = mod.__file__ if (modfile[(-4):] in ('.pyc', '.pyo')): modfile = modfile[:(-1)] elif modfile.endswith('$py.class'): modfile = (modfile[:(-9)] + '.py') if modfile.endswith((os.path.sep + '__init__.py')): if (self.basename != '__init__.py'): modfile = modfile[:(-12)] try: issame = self.samefile(modfile) except py.error.ENOENT: issame = False if (not issame): raise self.ImportMismatchError(modname, modfile, self) return mod else: try: return sys.modules[modname] except KeyError: mod = py.std.types.ModuleType(modname) mod.__file__ = str(self) sys.modules[modname] = mod try: py.builtin.execfile(str(self), mod.__dict__) except: del sys.modules[modname] raise return mod
'return stdout text from executing a system child process, where the \'self\' path points to executable. The process is directly invoked and not through a system shell.'
def sysexec(self, *argv, **popen_opts):
from subprocess import Popen, PIPE argv = map_as_list(str, argv) popen_opts['stdout'] = popen_opts['stderr'] = PIPE proc = Popen(([str(self)] + argv), **popen_opts) (stdout, stderr) = proc.communicate() ret = proc.wait() if py.builtin._isbytes(stdout): stdout = py.builtin._totext(stdout, sys.getdefaultencoding()) if (ret != 0): if py.builtin._isbytes(stderr): stderr = py.builtin._totext(stderr, sys.getdefaultencoding()) raise py.process.cmdexec.Error(ret, ret, str(self), stdout, stderr) return stdout
'return a path object found by looking at the systems underlying PATH specification. If the checker is not None it will be invoked to filter matching paths. If a binary cannot be found, None is returned Note: This is probably not working on plain win32 systems but may work on cygwin.'
def sysfind(cls, name, checker=None, paths=None):
if isabs(name): p = py.path.local(name) if p.check(file=1): return p else: if (paths is None): if iswin32: paths = py.std.os.environ['Path'].split(';') if (('' not in paths) and ('.' not in paths)): paths.append('.') try: systemroot = os.environ['SYSTEMROOT'] except KeyError: pass else: paths = [re.sub('%SystemRoot%', systemroot, path) for path in paths] else: paths = py.std.os.environ['PATH'].split(':') tryadd = [] if iswin32: tryadd += os.environ['PATHEXT'].split(os.pathsep) tryadd.append('') for x in paths: for addext in tryadd: p = (py.path.local(x).join(name, abs=True) + addext) try: if p.check(file=1): if checker: if (not checker(p)): continue return p except py.error.EACCES: pass return None
'return the system\'s temporary directory (where tempfiles are usually created in)'
def get_temproot(cls):
return py.path.local(py.std.tempfile.gettempdir())
'return a Path object pointing to a fresh new temporary directory (which we created ourself).'
def mkdtemp(cls, rootdir=None):
import tempfile if (rootdir is None): rootdir = cls.get_temproot() return cls(py.error.checked_call(tempfile.mkdtemp, dir=str(rootdir)))
'return unique directory with a number greater than the current maximum one. The number is assumed to start directly after prefix. if keep is true directories with a number less than (maxnum-keep) will be removed.'
def make_numbered_dir(cls, prefix='session-', rootdir=None, keep=3, lock_timeout=172800):
if (rootdir is None): rootdir = cls.get_temproot() def parse_num(path): ' parse the number out of a path (if it matches the prefix) ' bn = path.basename if bn.startswith(prefix): try: return int(bn[len(prefix):]) except ValueError: pass lastmax = None while True: maxnum = (-1) for path in rootdir.listdir(): num = parse_num(path) if (num is not None): maxnum = max(maxnum, num) try: udir = rootdir.mkdir((prefix + str((maxnum + 1)))) except py.error.EEXIST: if (lastmax == maxnum): raise lastmax = maxnum continue break if lock_timeout: lockfile = udir.join('.lock') mypid = os.getpid() if hasattr(lockfile, 'mksymlinkto'): lockfile.mksymlinkto(str(mypid)) else: lockfile.write(str(mypid)) def try_remove_lockfile(): if (os.getpid() != mypid): return try: lockfile.remove() except py.error.Error: pass atexit.register(try_remove_lockfile) if keep: for path in rootdir.listdir(): num = parse_num(path) if ((num is not None) and (num <= (maxnum - keep))): lf = path.join('.lock') try: t1 = lf.lstat().mtime t2 = lockfile.lstat().mtime if ((not lock_timeout) or (abs((t2 - t1)) < lock_timeout)): continue except py.error.Error: pass try: path.remove(rec=1) except KeyboardInterrupt: raise except: pass try: username = os.environ['USER'] except KeyError: try: username = os.environ['USERNAME'] except KeyError: username = 'current' src = str(udir) dest = ((src[:src.rfind('-')] + '-') + username) try: os.unlink(dest) except OSError: pass try: os.symlink(src, dest) except (OSError, AttributeError, NotImplementedError): pass return udir
'prune out entries with lowest weight.'
def _prunelowestweight(self):
numentries = len(self._dict) if (numentries >= self.maxentries): items = [(entry.weight, key) for (key, entry) in self._dict.items()] items.sort() index = (numentries - self.prunenum) if (index > 0): for (weight, key) in items[:index]: self.delentry(key, raising=False)
'execute an svn command, append our own url and revision'
def _svnwithrev(self, cmd, *args):
if (self.rev is None): return self._svnwrite(cmd, *args) else: args = (['-r', self.rev] + list(args)) return self._svnwrite(cmd, *args)
'execute an svn command, append our own url'
def _svnwrite(self, cmd, *args):
l = [('svn %s' % cmd)] args = [('"%s"' % self._escape(item)) for item in args] l.extend(args) l.append(('"%s"' % self._encodedurl())) string = ' '.join(l) if DEBUG: print ('execing %s' % string) out = self._svncmdexecauth(string) return out
'execute an svn command \'as is\''
def _svncmdexecauth(self, cmd):
cmd = (svncommon.fixlocale() + cmd) if (self.auth is not None): cmd += (' ' + self.auth.makecmdoptions()) return self._cmdexec(cmd)