示例#1
0
def chdir(path):
    """chdir(path)

    Change the current working directory to the specified path.
    """
    realpath = _path.realpath(path)
    if not _path.exists(realpath):
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    if not _path.isdir(realpath):
        raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path)
    sys.setCurrentWorkingDir(realpath)
示例#2
0
def rmdir(path):
    """rmdir(path)

    Remove a directory."""
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    elif not f.isDirectory():
        raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path)
    elif not f.delete():
        raise OSError(0, "couldn't delete directory", path)
示例#3
0
    def __init__(self, filename, *, write=False, new=False, perror=False):
        ''' Open/create a CRAB file.

            If `write` is True, the data in the file may be written
            directly.  This is not needed for ordinary section manipulation,
            and should be used with extreme caution.

            If `new` is True, an existing file will not be opened, but the
            filename will still be used when `save()` is called.

            If `perror` is True, errors will be sent to stderr as well as
            raising a python exception. Note that unrecoverable errors also
            exist.
        '''
        # forced - it exists for our benefit, after all!
        flags = _lib.CRAB_FILE_FLAG_ERROR
        if write:
            flags |= _lib.CRAB_FILE_FLAG_WRITE
        if new:
            flags |= _lib.CRAB_FILE_FLAG_NEW
        if perror:
            flags |= _lib.CRAB_FILE_FLAG_PERROR
        raw = _lib.crab_file_open(filename.encode('utf-8'), flags)
        if raw == _ffi.NULL:
            raise OSError(_ffi.errno, 'malloc: %s' % errno.strerror(_ffi.errno))
        self._raw = _ffi.gc(raw, _lib.crab_file_close)
        self.raise_error(always=False)
示例#4
0
def fdopen(fd, mode='r', bufsize=-1):
    """fdopen(fd [, mode='r' [, bufsize]]) -> file_object

    Return an open file object connected to a file descriptor.
    """
    rawio = FileDescriptors.get(fd)
    if (len(mode) and mode[0] or '') not in 'rwa':
        raise ValueError("invalid file mode '%s'" % mode)
    if rawio.closed():
        raise OSError(errno.EBADF, errno.strerror(errno.EBADF))

    try:
        fp = FileDescriptors.wrap(rawio, mode, bufsize)
    except IOError:
        raise OSError(errno.EINVAL, errno.strerror(errno.EINVAL))
    return fp
示例#5
0
def stat(path):
    """stat(path) -> stat result

    Perform a stat system call on the given path.

    The Java stat implementation only returns a small subset of
    the standard fields: size, modification time and change time.
    """
    abs_path = sys.getPath(path)
    try:
        return stat_result.from_jnastat(_posix.stat(abs_path))
    except NotImplementedError:
        pass
    except:
        raise
    f = File(abs_path)
    if not f.exists():
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    size = f.length()
    mtime = f.lastModified() / 1000.0
    mode = 0
    if f.isDirectory():
        mode = _stat.S_IFDIR
    elif f.isFile():
        mode = _stat.S_IFREG
    if f.canRead():
        mode = mode | _stat.S_IREAD
    if f.canWrite():
        mode = mode | _stat.S_IWRITE
    return stat_result((mode, 0, 0, 0, 0, 0, size, mtime, mtime, 0))
示例#6
0
def ftruncate(fd, length):
    """ftruncate(fd, length)

    Truncate a file to a specified length.
    """
    rawio = FileDescriptors.get(fd)
    try:
        rawio.truncate(length)
    except Exception, e:
        raise IOError(errno.EBADF, errno.strerror(errno.EBADF))
示例#7
0
def strerror(code):
    """strerror(code) -> string

    Translate an error code to a message string.
    """
    if not isinstance(code, (int, long)):
        raise TypeError('an integer is required')
    try:
        return errno.strerror(code)
    except KeyError:
        return 'Unknown error: %d' % code
示例#8
0
def chmod(path, mode):
    """chmod(path, mode)

    Change the access permissions of a file.
    """
    # XXX no error handling for chmod in jna-posix
    # catch not found errors explicitly here, for now
    abs_path = sys.getPath(path)
    if not File(abs_path).exists():
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    _posix.chmod(abs_path, mode)
示例#9
0
def open(filename, flag, mode=0777):
    """open(filename, flag [, mode=0777]) -> fd

    Open a file (for low level IO).
    """
    reading = flag & O_RDONLY
    writing = flag & O_WRONLY
    updating = flag & O_RDWR
    creating = flag & O_CREAT

    truncating = flag & O_TRUNC
    exclusive = flag & O_EXCL
    sync = flag & O_SYNC
    appending = flag & O_APPEND

    if updating and writing:
        raise OSError(errno.EINVAL, errno.strerror(errno.EINVAL), filename)

    if not creating and not path.exists(filename):
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), filename)

    if not writing:
        if updating:
            writing = True
        else:
            reading = True

    if truncating and not writing:
        # Explicitly truncate, writing will truncate anyway
        FileIO(filename, 'w').close()

    if exclusive and creating:
        try:
            if not File(sys.getPath(filename)).createNewFile():
                raise OSError(errno.EEXIST, errno.strerror(errno.EEXIST),
                              filename)
        except java.io.IOException, ioe:
            raise OSError(ioe)
示例#10
0
def mkdir(path, mode='ignored'):
    """mkdir(path [, mode=0777])

    Create a directory.

    The optional parameter is currently ignored.
    """
    # XXX: use _posix.mkdir when we can get the real errno upon failure
    fp = File(sys.getPath(path))
    if not fp.mkdir():
        if fp.isDirectory() or fp.isFile():
            err = errno.EEXIST
        else:
            err = 0
        msg = errno.strerror(err) if err else "couldn't make directory"
        raise OSError(err, msg, path)
示例#11
0
    def raise_error(self, *, always=True):
        ''' Utility function to turn message+errno pairs into exceptions.

            Usually this library will take care of this all for you.
        '''
        msg_ptr = _ffi.new('char **')
        no_ptr = _ffi.new('int *')
        _lib.crab_file_error(self._raw, msg_ptr, no_ptr)
        msg = msg_ptr[0]
        no = no_ptr[0]
        if msg == _ffi.NULL:
            if not always:
                return
            raise TypeError('expected an error to exist!')
        msg = _ffi.string(msg).decode('ascii')
        raise OSError(no, '%s: %s' % (msg, errno.strerror(no)))
示例#12
0
def lstat(path):
    """lstat(path) -> stat result

    Like stat(path), but do not follow symbolic links.
    """
    abs_path = sys.getPath(path)
    try:
        return stat_result.from_jnastat(_posix.lstat(abs_path))
    except NotImplementedError:
        pass
    except:
        raise
    f = File(sys.getPath(path))
    abs_parent = f.getAbsoluteFile().getParentFile()
    if not abs_parent:
      # root isn't a link
      return stat(path)
    can_parent = abs_parent.getCanonicalFile()

    if can_parent.getAbsolutePath() == abs_parent.getAbsolutePath():
        # The parent directory's absolute path is canonical..
        if f.getAbsolutePath() != f.getCanonicalPath():
            # but the file's absolute and canonical paths differ (a
            # link)
            return stat_result((_stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))

    # The parent directory's path is not canonical (one of the parent
    # directories is a symlink). Build a new path with the parent's
    # canonical path and compare the files
    f = File(_path.join(can_parent.getAbsolutePath(), f.getName()))
    if f.getAbsolutePath() != f.getCanonicalPath():
        return stat_result((_stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))

    # Not a link, only now can we determine if it exists (because
    # File.exists() returns False for dead links)
    if not f.exists():
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    return stat(path)
示例#13
0
def errcheck(result, func, args):
    if result < 0:
        e = ctypes.get_errno()
        raise OSError(e, errno.strerror(e))
    return result
示例#14
0
                              filename)
        except java.io.IOException, ioe:
            raise OSError(ioe)

    mode = '%s%s%s%s' % (reading and 'r' or '',
                         (not appending and writing) and 'w' or '',
                         (appending and (writing or updating)) and 'a' or '',
                         updating and '+' or '')

    if sync and (writing or updating):
        from java.io import FileNotFoundException, RandomAccessFile
        try:
            fchannel = RandomAccessFile(sys.getPath(filename), 'rws').getChannel()
        except FileNotFoundException, fnfe:
            if path.isdir(filename):
                raise OSError(errno.EISDIR, errno.strerror(errno.EISDIR))
            raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), filename)
        return FileIO(fchannel, mode)

    return FileIO(filename, mode)

def read(fd, buffersize):
    """read(fd, buffersize) -> string

    Read a file descriptor.
    """
    from org.python.core.util import StringUtil
    rawio = FileDescriptors.get(fd)
    buf = _handle_oserror(rawio.read, buffersize)
    return asPyString(StringUtil.fromBytes(buf))
示例#15
0
 def error(self, error, msg):
     err = getattr(errno, error.name(), None)
     if err is None:
         raise OSError('%s: %s' % (error, msg))
     raise OSError(err, errno.strerror(err), msg)
示例#16
0
def _handle_oserror(func, *args, **kwargs):
    """Translate exceptions into OSErrors"""
    try:
        return func(*args, **kwargs)
    except:
        raise OSError(errno.EBADF, errno.strerror(errno.EBADF))
示例#17
0
def errcheck(result, func, args):
    if result < 0:
        e = ctypes.get_errno()
        raise OSError(e, errno.strerror(e))
    return result