示例#1
0
def rename(path, newpath):
    """rename(old, new)

    Rename a file or directory.
    """
    if not File(sys.getPath(path)).renameTo(File(sys.getPath(newpath))):
        raise OSError(0, "couldn't rename file", path)
示例#2
0
def rename(path, newpath):
    """rename(old, new)

    Rename a file or directory.
    """
    if not File(sys.getPath(path)).renameTo(File(sys.getPath(newpath))):
        raise OSError(0, "couldn't rename file", path)
示例#3
0
    def readlink(path):
        """readlink(path) -> path

        Return a string representing the path to which the symbolic link
        points.
        """
        return _posix.readlink(sys.getPath(path))
示例#4
0
def remove(path):
    """remove(path)

    Remove a file (same as unlink(path)).
    """
    if not File(sys.getPath(path)).delete():
        raise OSError(0, "couldn't delete file", path)
示例#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 access(path, mode):
    """access(path, mode) -> True if granted, False otherwise

    Use the real uid/gid to test for access to a path.  Note that most
    operations will use the effective uid/gid, therefore this routine can
    be used in a suid/sgid environment to test if the invoking user has the
    specified access to the path.  The mode argument can be F_OK to test
    existence, or the inclusive-OR of R_OK, W_OK, and X_OK.
    """
    if not isinstance(mode, (int, long)):
        raise TypeError('an integer is required')

    f = File(sys.getPath(path))
    result = True
    if not f.exists():
        result = False
    if mode & R_OK and not f.canRead():
        result = False
    if mode & W_OK and not f.canWrite():
        result = False
    if mode & X_OK:
        # NOTE: always False without jna-posix stat
        try:
            result = (stat(path).st_mode & _stat.S_IEXEC) != 0
        except OSError:
            result = False
    return result
示例#7
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, 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))
示例#8
0
def access(path, mode):
    """access(path, mode) -> True if granted, False otherwise

    Use the real uid/gid to test for access to a path.  Note that most
    operations will use the effective uid/gid, therefore this routine can
    be used in a suid/sgid environment to test if the invoking user has the
    specified access to the path.  The mode argument can be F_OK to test
    existence, or the inclusive-OR of R_OK, W_OK, and X_OK.
    """
    if not isinstance(mode, (int, long)):
        raise TypeError('an integer is required')

    f = File(sys.getPath(path))
    result = True
    if not f.exists():
        result = False
    if mode & R_OK and not f.canRead():
        result = False
    if mode & W_OK and not f.canWrite():
        result = False
    if mode & X_OK:
        # NOTE: always False without jna-posix stat
        try:
            result = (stat(path).st_mode & _stat.S_IEXEC) != 0
        except OSError:
            result = False
    return result
示例#9
0
def remove(path):
    """remove(path)

    Remove a file (same as unlink(path)).
    """
    if not File(sys.getPath(path)).delete():
        raise OSError(0, "couldn't delete file", path)
示例#10
0
    def readlink(path):
        """readlink(path) -> path

        Return a string representing the path to which the symbolic link
        points.
        """
        return _posix.readlink(sys.getPath(path))
示例#11
0
def getatime(path):
    # We can't detect access time so we return modification time. This
    # matches the behaviour in os.stat().
    path = _tostr(path, "getatime")
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(0, 'No such file or directory', path)
    return f.lastModified() / 1000.0
示例#12
0
def exists(path):
    """Test whether a path exists.

    Returns false for broken symbolic links.

    """
    path = _tostr(path, "exists")
    return File(sys.getPath(path)).exists()
示例#13
0
def getatime(path):
    # We can't detect access time so we return modification time. This
    # matches the behaviour in os.stat().
    path = _tostr(path, "getatime")
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(0, "No such file or directory", path)
    return f.lastModified() / 1000.0
示例#14
0
def exists(path):
    """Test whether a path exists.

    Returns false for broken symbolic links.

    """
    path = _tostr(path, "exists")
    return File(sys.getPath(path)).exists()
示例#15
0
文件: os.py 项目: babble/babble
def mkdir(path, mode='ignored'):
    """mkdir(path [, mode=0777])

    Create a directory.

    The optional parameter is currently ignored.
    """
    if not File(sys.getPath(path)).mkdir():
        raise OSError(0, "couldn't make directory", path)
示例#16
0
def getsize(path):
    path = _tostr(path, "getsize")
    f = File(sys.getPath(path))
    size = f.length()
    # Sadly, if the returned length is zero, we don't really know if the file
    # is zero sized or does not exist.
    if size == 0 and not f.exists():
        raise OSError(0, 'No such file or directory', path)
    return size
示例#17
0
def getsize(path):
    path = _tostr(path, "getsize")
    f = File(sys.getPath(path))
    size = f.length()
    # Sadly, if the returned length is zero, we don't really know if the file
    # is zero sized or does not exist.
    if size == 0 and not f.exists():
        raise OSError(0, "No such file or directory", path)
    return size
示例#18
0
    def abspath(path):
        """Return the absolute version of a path."""
        try:
            if isinstance(path, unicode):
                if path:
                    path = sys.getPath(path)
                else:
                    # Empty path must return current working directory
                    path = os.getcwdu()
            else:
                if path:
                    path = sys.getPath(path).encode('latin-1')
                else:
                    # Empty path must return current working directory
                    path = os.getcwd()
        except EnvironmentError:
             pass # Bad path - return unchanged.

        return normpath(path)
示例#19
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, strerror(errno.ENOENT), path)
    _posix.chmod(abs_path, mode)
示例#20
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)
示例#21
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)
示例#22
0
def rmdir(path):
    """rmdir(path)

    Remove a directory."""
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(errno.ENOENT, strerror(errno.ENOENT), path)
    elif not f.isDirectory():
        raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path)
    elif not f.delete():
        raise OSError(0, "couldn't delete directory", path)
示例#23
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))
    # XXX: jna-posix implements similar link detection in
    # JavaFileStat.calculateSymlink, fallback to that instead when not
    # native
    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, strerror(errno.ENOENT), path)
    return stat(path)
示例#24
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))
    # XXX: jna-posix implements similar link detection in
    # JavaFileStat.calculateSymlink, fallback to that instead when not
    # native
    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, strerror(errno.ENOENT), path)
    return stat(path)
示例#25
0
def listdir(path):
    """listdir(path) -> list_of_strings

    Return a list containing the names of the entries in the directory.

        path: path of directory to list

    The list is in arbitrary order.  It does not include the special
    entries '.' and '..' even if they are present in the directory.
    """
    l = File(sys.getPath(path)).list()
    if l is None:
        raise OSError(0, 'No such directory', path)
    return [asPyString(entry) for entry in l]
示例#26
0
def listdir(path):
    """listdir(path) -> list_of_strings

    Return a list containing the names of the entries in the directory.

        path: path of directory to list

    The list is in arbitrary order.  It does not include the special
    entries '.' and '..' even if they are present in the directory.
    """
    l = File(sys.getPath(path)).list()
    if l is None:
        raise OSError(0, 'No such directory', path)
    return [asPyString(entry) for entry in l]
示例#27
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 = strerror(err) if err else "couldn't make directory"
        raise OSError(err, msg, path)
示例#28
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)
示例#29
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)
示例#30
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, strerror(errno.EINVAL), filename)

    if not creating and not path.exists(filename):
        raise OSError(errno.ENOENT, 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, strerror(errno.EEXIST),
                              filename)
        except java.io.IOException, ioe:
            raise OSError(ioe)
示例#31
0
def makedirs(path, mode='ignored'):
    """makedirs(path [, mode=0777])

    Super-mkdir; create a leaf directory and all intermediate ones.

    Works like mkdir, except that any intermediate path segment (not
    just the rightmost) will be created if it does not exist.
    The optional parameter is currently ignored.
    """
    sys_path = sys.getPath(path)
    if File(sys_path).mkdirs():
        return

    # if making a /x/y/z/., java.io.File#mkdirs inexplicably fails. So we need
    # to force it

    # need to use _path instead of path, because param is hiding
    # os.path module in namespace!
    head, tail = _path.split(sys_path)
    if tail == curdir:
        if File(_path.join(head)).mkdirs():
            return

    raise OSError(0, "couldn't make directories", path)
示例#32
0
def makedirs(path, mode='ignored'):
    """makedirs(path [, mode=0777])

    Super-mkdir; create a leaf directory and all intermediate ones.

    Works like mkdir, except that any intermediate path segment (not
    just the rightmost) will be created if it does not exist.
    The optional parameter is currently ignored.
    """
    sys_path = sys.getPath(path)
    if File(sys_path).mkdirs():
        return

    # if making a /x/y/z/., java.io.File#mkdirs inexplicably fails. So we need
    # to force it

    # need to use _path instead of path, because param is hiding
    # os.path module in namespace!
    head, tail = _path.split(sys_path)
    if tail == curdir:
        if File(_path.join(head)).mkdirs():
            return

    raise OSError(0, "couldn't make directories", path)
示例#33
0
def isdir(path):
    """Test whether a path is a directory"""
    path = _tostr(path, "isdir")
    return File(sys.getPath(path)).isDirectory()
示例#34
0
def isfile(path):
    """Test whether a path is a regular file"""
    path = _tostr(path, "isfile")
    return File(sys.getPath(path)).isFile()
示例#35
0
        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)

    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)
示例#36
0
    def symlink(src, dst):
        """symlink(src, dst)

        Create a symbolic link pointing to src named dst.
        """
        _posix.symlink(src, sys.getPath(dst))
示例#37
0
def getmtime(path):
    path = _tostr(path, "getmtime")
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(0, "No such file or directory", path)
    return f.lastModified() / 1000.0
示例#38
0
def _abspath(path):
    # Must use normpath separately because getAbsolutePath doesn't normalize
    # and getCanonicalPath would eliminate symlinks.
    return normpath(asPyString(File(sys.getPath(path)).getAbsolutePath()))
示例#39
0
def isdir(path):
    """Test whether a path is a directory"""
    path = _tostr(path, "isdir")
    return File(sys.getPath(path)).isDirectory()
示例#40
0
文件: os.py 项目: babble/babble
def rmdir(path):
    """rmdir(path)

    Remove a directory."""
    if not File(sys.getPath(path)).delete():
        raise OSError(0, "couldn't delete directory", path)
示例#41
0
    if exclusive and creating:
        try:
            if not File(sys.getPath(filename)).createNewFile():
                raise OSError(errno.EEXIST, strerror(errno.EEXIST), 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, strerror(errno.EISDIR))
            raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename)
        return FileIO(fchannel, mode)

    return FileIO(filename, mode)


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

    Read a file descriptor.
    """
示例#42
0
    def symlink(src, dst):
        """symlink(src, dst)

        Create a symbolic link pointing to src named dst.
        """
        _posix.symlink(src, sys.getPath(dst))
示例#43
0
    def link(src, dst):
        """link(src, dst)

        Create a hard link to a file.
        """
        _posix.link(sys.getPath(src), sys.getPath(dst))
示例#44
0
def _abspath(path):
    # Must use normpath separately because getAbsolutePath doesn't normalize
    # and getCanonicalPath would eliminate symlinks.
    return normpath(asPyString(File(sys.getPath(path)).getAbsolutePath()))
示例#45
0
def _realpath(path):
    try:
        return asPyString(File(sys.getPath(path)).getCanonicalPath())
    except java.io.IOException:
        return _abspath(path)
示例#46
0
def _realpath(path):
    try:
        return asPyString(File(sys.getPath(path)).getCanonicalPath())
    except java.io.IOException:
        return _abspath(path)
示例#47
0
def getmtime(path):
    path = _tostr(path, "getmtime")
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(0, 'No such file or directory', path)
    return f.lastModified() / 1000.0
示例#48
0
    def link(src, dst):
        """link(src, dst)

        Create a hard link to a file.
        """
        _posix.link(sys.getPath(src), sys.getPath(dst))
示例#49
0
def isfile(path):
    """Test whether a path is a regular file"""
    path = _tostr(path, "isfile")
    return File(sys.getPath(path)).isFile()
示例#50
0
        try:
            if not File(sys.getPath(filename)).createNewFile():
                raise OSError(errno.EEXIST, strerror(errno.EEXIST),
                              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, strerror(errno.EISDIR))
            raise OSError(errno.ENOENT, 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)