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:
... |
'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,... | 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()
... |
'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 getat... |
'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
... |
'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 ((c... |
'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 = se... |
'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... | 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.f... |
'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, __... |
'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 ... |
'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(... |
'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 Ke... |
'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
... |
'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[ta... |
'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... |
'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._sav... |
'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.st... |
'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,)))
... |
'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 simpl... | 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:
... |
'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:
... |
'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 h... |
'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)):
rais... |
'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 = p... |
'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, ar... |
'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 exist... |
'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... |
'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:
... |
'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 ... | 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)] == '__i... |
'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(std... |
'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(... |
'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):])
... |
'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(ke... |
'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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.